It takes an Array and inserts an element to the specified index - Java Collection Framework

Java examples for Collection Framework:Array Auto Increment

Description

It takes an Array and inserts an element to the specified index

Demo Code


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

public class Main {
    /**/*w w  w .  j  av  a2 s . c  o m*/
     *
     * /**
     * It takes an Array and inserts an element to the specified index
     *
     * @param <T> Type
     * @param typeClass the class of the type of the array
     * @param array the array you want to operate on
     * @param index the index where you want to insert the element
     * @param element the element you want to add
     * @return the new extended array
     */
    public static <T> T[] insertElement(Class<T> typeClass, T[] array,
            int index, T element) {
        if (index > array.length - 1) {
            return addElement(typeClass, array, element);
        }
        @SuppressWarnings("unchecked")
        T[] newArray = (T[]) Array.newInstance(typeClass, array.length + 1);
        int newArrayIndex = 0;

        for (int originalArrayIndex = 0; originalArrayIndex < array.length; originalArrayIndex++) {
            if (newArrayIndex == index) {
                newArray[newArrayIndex] = element;
                newArrayIndex++;
            }
            newArray[newArrayIndex] = array[originalArrayIndex];
            newArrayIndex++;
        }
        return newArray;
    }

    /**
     * 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