This post will discuss how to remove an element at the specified position from a primitive integer array in Java.

We know that Java arrays are fixed-length, unlike ArrayList, which is dynamic. Therefore, Java doesn’t permit the removal of an element at the specified position in an array. This post provides an overview of some of the available alternatives to accomplish this.

1. Using Java 8 Stream

The recommended approach is to use Stream in Java 8 and above, as shown below:

Download  Run Code

Output:

[1, 2, 4, 5]

2. Using ArrayList

Another plausible way of removing an element at the specified position from the specified array involves using the List data structure, as demonstrated below:

  1. Insert all array elements into a ArrayList.
  2. Remove the element present at the specified position in the ArrayList using remove() method.
  3. Convert the ArrayList back to the array and return it.

Download  Run Code

Output:

[1, 2, 4, 5]

3. Using System.arraycopy() method

Another efficient solution is to make two calls to System.arraycopy(), which can copy an array from the specified source array, beginning at the specified position, to the specified position in the destination array.

Download  Run Code

Output:

[1, 2, 4, 5]

4. Naive solution

Instead of using System.arraycopy(), we can write our own routine, which logically works in a similar way. The idea is to declare a new array with one less element and copy the relevant values from the original array into the new array.

Download  Run Code

Output:

[1, 2, 4, 5]

5. Using Apache Commons Lang

We can also leverage Apache Commons Lang’s ArrayUtils class, which offers the remove() method.

Download Code

That’s all about removing an element at a specific index from an array in Java.