It takes an Array and removes an element at the specified index - Java Collection Framework

Java examples for Collection Framework:Array Auto Increment

Description

It takes an Array and removes an element at the specified index

Demo Code


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

public class Main {
    /**//  w ww. j  av a 2  s.c  om
     * It takes an Array and removes an element at 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 of the element you want to remove
     * @return the new reduced array
     */
    public static <T> T[] removeElementAtIndex(Class<T> typeClass,
            T[] array, int index) {
        @SuppressWarnings("unchecked")
        T[] newArray = (T[]) Array.newInstance(typeClass, array.length - 1);
        int newArrayIndex = 0;
        for (int originalArrayIndex = 0; originalArrayIndex < array.length; originalArrayIndex++) {
            if (originalArrayIndex != index) {
                newArray[newArrayIndex] = array[originalArrayIndex];
                newArrayIndex++;
            }
        }
        return newArray;
    }
}

Related Tutorials