It takes an Array and add the specified element to the end of the it - Java Collection Framework

Java examples for Collection Framework:Array Auto Increment

Description

It takes an Array and add the specified element to the end of the it

Demo Code


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

public class Main {
    /**/*from   ww w  .ja v  a2s.c o m*/
     * It takes an Array and add the specified element to the end of the it
     *
     * @param <T> Type
     * @param typeClass the class of the type of the array
     * @param array the array you want to operate on
     * @param element the element you want to add
     * @return the new extended array
     */
    public static <T> T[] addElement(Class<T> typeClass, T[] array,
            T element) {
        @SuppressWarnings("unchecked")
        T[] newArray = (T[]) Array.newInstance(typeClass, array.length + 1);
        int i = 0;
        while (i < array.length) {
            newArray[i] = array[i];
            i++;
        }
        newArray[i] = element;

        return newArray;
    }
}

Related Tutorials