resize an array - Java Collection Framework

Java examples for Collection Framework:Array Length

Description

resize an array

Demo Code


//package com.book2s;
import java.lang.reflect.Array;

public class Main {

    public static <T> T[] resize(T[] buffer, int newSize,
            Class<?> componentType) {
        T[] newArray = newArray(componentType, newSize);
        System.arraycopy(buffer, 0, newArray, 0,
                buffer.length >= newSize ? newSize : buffer.length);
        return newArray;
    }/* w ww.  j a v  a 2 s . c  o m*/

    public static <T> T[] resize(T[] buffer, int newSize) {
        return resize(buffer, newSize, buffer.getClass().getComponentType());
    }

    @SuppressWarnings("unchecked")
    public static <T> T[] newArray(Class<?> componentType, int newSize) {
        return (T[]) Array.newInstance(componentType, newSize);
    }
}

Related Tutorials