Removing Objects from an Array in Java
In Java, arrays are fixed-length collections of elements. When you need to remove an object from an array, there is no straightforward built-in method to do so.
Consider an array of strings:
String[] foo = { "a", "cc", "a", "dd" };
Solution: Array to List and Back
One approach to remove objects from an array is to convert it to a list, modify the list, and then convert it back to an array.
List<String> list = new ArrayList<>(Arrays.asList(foo)); list.removeAll(Arrays.asList("a")); foo = list.toArray(foo);
This process retains the original array's size, with the elements after the last remaining element set to null.
Solution: New Array from List
If you want a new array exactly the size needed, you can do the following:
foo = list.toArray(new String[list.size()]);
Using Reusables
For frequent usage, you might consider creating a pre-defined empty string array constant:
private static final String[] EMPTY_STRING_ARRAY = new String[0];
Then, the removal function can be rewritten as:
List<String> list = new ArrayList<> (); Collections.addAll(list, foo); list.removeAll(Arrays.asList("a")); foo = list.toArray(EMPTY_STRING_ARRAY);
Alternatively, you can use the approach suggested by cynicalman:
foo = list.toArray(new String[list.size()]);
The above is the detailed content of How Can I Efficiently Remove Objects from a Java Array?. For more information, please follow other related articles on the PHP Chinese website!