Close

Java - How to remove array element by index?

[Last Updated: May 23, 2018]

Java Arrays Java 

Following code shows how to remove an array element by index.

package com.logicbig.example;

import java.lang.reflect.Array;
import java.util.Arrays;

public class ArrayRemove {

  public static <T> T[] removeByIndex(T[] array, int index) {
      int newLen = array.length - 1;
      @SuppressWarnings("unchecked")
      T[] c = (T[]) Array.newInstance(array.getClass().getComponentType(), newLen);
      System.arraycopy(array, 0, c, 0, index);
      System.arraycopy(array, index + 1, c, index, newLen - index);
      return c;
  }

  public static void main(String[] args) {
      Integer[] i = {1, 4, 5, 6, 7};
      System.out.println("given array: "+Arrays.toString(i));

      Integer[] n = removeByIndex(i, 4);
      System.out.println("removed at 4: "+ Arrays.toString(n));

      n = removeByIndex(i, 0);
      System.out.println("removed at 0: "+ Arrays.toString(n));

      n = removeByIndex(i, 2);
      System.out.println("removed at 2: "+ Arrays.toString(n));
  }
}
given array: [1, 4, 5, 6, 7]
removed at 4: [1, 4, 5, 6]
removed at 0: [4, 5, 6, 7]
removed at 2: [1, 4, 6, 7]

See Also