append element to an array - Java Collection Framework

Java examples for Collection Framework:Array Auto Increment

Description

append element to an array

Demo Code


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

public class Main {

    public static <T> T[] append(T[] buffer, T newElement) {
        T[] t = resize(buffer, buffer.length + 1, newElement.getClass());
        t[buffer.length] = newElement;/*from ww w .j  a v a2s . co  m*/
        return t;
    }

    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;
    }

    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