I need to delete some objects from an ArrayList if they meet a condition and I'm wondering which way could be more efficient.
Here's the situation: I have a class that contains an ArrayList containing some other objects. I have to iterate over this ArrayList and delete all elements meeting a certain condition.
As far as I know, those would be my options to delete:
Create a new ArrayList and add the elements that doesn't meet the condition. After the iteration, swap from the old arraylist to the new one without the elements.
Create a new ArrayList and add the elements that meet the condition. After the iteration, use the removeAll() method passing the ArrayList with the objects to be deleted.
Is there a more efficient way to delete objects from an ArrayList?
解决方案
Another way: The Iterator has an optional remove()-method, that is implemented for ArrayList. You can use it while iterating.
I don't know though, which variant is the most performant, you should measure it.
starblue commented, that the complexity isn't good, and that's true (for removeAll() too), because ArrayList has to copy all elements, if in the middle is an element added or removed. For that cases should a LinkedList work better. But, as we all don't know your real use-cases the best is too measure all variants, to pick the best solution.