Skip to main content

How do I remove elements from an Array

In this Q&A, we'll go over how to remove or add elements from an array

If elements have to be added or removed from an array consider using ArrayList.  Assuming that's not feasible, if an element has to be removed then steps involved are:
- create a new array with the reduced size
- copy all the elements to the new array excluding the one that has to be removed

Apache lang commons ArrayUtils class provides a remove() method that does the above.  See demo code below:
int[] ia = {1,2,3,4};
int[] ia2 = ArrayUtils.remove(ia, 2);
System.out.println(ia2.length);

ArrayUtils class also provides functions to add elements at the end or at any specified index

Comments