Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting objects from an ArrayList in Java

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:

  1. 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.

  2. 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?

like image 485
Carlos Pastor Avatar asked Aug 21 '09 07:08

Carlos Pastor


People also ask

How do you remove multiple objects from an ArrayList in Java?

Core Java bootcamp program with Hands on practice The List provides removeAll() method to remove all elements of a list that are part of the collection provided.

How do I remove an Object from a collection in Java?

An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown.


1 Answers

You could iterate backwards and remove as you go through the ArrayList. This has the advantage of subsequent elements not needing to shift and is easier to program than moving forwards.

like image 137
RichardOD Avatar answered Oct 14 '22 15:10

RichardOD