Remove an element from an array
suggest changeJava doesn’t provide a direct method in java.util.Arrays
to remove an element from an array. To perform it, you can either copy the original array to a new one without the element to remove or convert your array to another structure allowing the removal.
Using ArrayList
You can convert the array to a java.util.List
, remove the element and convert the list back to an array as follows:
String[] array = new String[]{"foo", "bar", "baz"}; List<String> list = new ArrayList<>(Arrays.asList(array)); list.remove("foo"); // Creates a new array with the same size as the list and copies the list // elements to it. array = list.toArray(new String[list.size()]); System.out.println(Arrays.toString(array)); //[bar, baz]
Using System.arraycopy
System.arraycopy()
can be used to make a copy of the original array and remove the element you want. Below an example:
int[] array = new int[] { 1, 2, 3, 4 }; // Original array. int[] result = new int[array.length - 1]; // Array which will contain the result. int index = 1; // Remove the value "2". // Copy the elements at the left of the index. System.arraycopy(array, 0, result, 0, index); // Copy the elements at the right of the index. System.arraycopy(array, index + 1, result, index, array.length - index - 1); System.out.println(Arrays.toString(result)); //[1, 3, 4]
Using Apache Commons Lang
To easily remove an element, you can use the Apache Commons Lang library and especially the static method removeElement()
of the class ArrayUtils
. Below an example:
int[] array = new int[]{1,2,3,4}; array = ArrayUtils.removeElement(array, 2); //remove first occurrence of 2 System.out.println(Arrays.toString(array)); //[1, 3, 4]
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents