Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove objects from an array in Java?

Given an array of n Objects, let's say it is an array of strings, and it has the following values:

foo[0] = "a"; foo[1] = "cc"; foo[2] = "a"; foo[3] = "dd"; 

What do I have to do to delete/remove all the strings/objects equal to "a" in the array?

like image 234
Rodrigo Amaya Avatar asked Sep 21 '08 23:09

Rodrigo Amaya


People also ask

Can you remove an object from an array?

There are different methods and techniques you can use to remove elements from JavaScript arrays: pop - Removes from the End of an Array. shift - Removes from the beginning of an Array. splice - removes from a specific Array index.

How do you remove multiple elements from an array in Java?

First Create an empty List of Array. Insert all elements of the array into the list. Remove all those element which is you want to remove using the equals() method. Convert the list back to an array and return it.


1 Answers

[If you want some ready-to-use code, please scroll to my "Edit3" (after the cut). The rest is here for posterity.]

To flesh out Dustman's idea:

List<String> list = new ArrayList<String>(Arrays.asList(array)); list.removeAll(Arrays.asList("a")); array = list.toArray(array); 

Edit: I'm now using Arrays.asList instead of Collections.singleton: singleton is limited to one entry, whereas the asList approach allows you to add other strings to filter out later: Arrays.asList("a", "b", "c").

Edit2: The above approach retains the same array (so the array is still the same length); the element after the last is set to null. If you want a new array sized exactly as required, use this instead:

array = list.toArray(new String[0]); 

Edit3: If you use this code on a frequent basis in the same class, you may wish to consider adding this to your class:

private static final String[] EMPTY_STRING_ARRAY = new String[0]; 

Then the function becomes:

List<String> list = new ArrayList<>(); Collections.addAll(list, array); list.removeAll(Arrays.asList("a")); array = list.toArray(EMPTY_STRING_ARRAY); 

This will then stop littering your heap with useless empty string arrays that would otherwise be newed each time your function is called.

cynicalman's suggestion (see comments) will also help with the heap littering, and for fairness I should mention it:

array = list.toArray(new String[list.size()]); 

I prefer my approach, because it may be easier to get the explicit size wrong (e.g., calling size() on the wrong list).

like image 196
Chris Jester-Young Avatar answered Oct 08 '22 21:10

Chris Jester-Young