Is there any accepted best practice in Java for removing a list item during iteration over a list?

I find conflicting tips on the best way to avoid ConcurrentModificationExceptionthis:

    List<Apple> Apples = appleCart.getApples();
    for (Apple apple : Apples)
    {
        delete(apple);
    }

I tend to use Iteratorinstead Listand calling its method remove.

Does this make sense?

+3
source share
4 answers

Yes, use Iterator. Then you can use its delete method.

  for (Iterator<Apple> appleIterator = Apples.iterator(); appleIterator.hasNext();) {
     Apple apple = appleIterator.next();
     if (apple.isTart()) {
        appleIterator.remove();
     }
  }
}
+5
source

If you get a ConcurrentModificationException, you are likely to have multiple threads.

Thus, the complete answer includes both using Iterator.remove () and synchronizing access to the collection.

( , ):

synchronized ( lock ) {
   List<Apple> apples = appleCart.getApples();
   for ( Iterator<Apple> it = apples.iterator(); it.hasNext(); )
   {
      Apple a = it.next(); 
      if ( a.hasWorm() ) {
         it.remove();
      }
   }
}
+2
List<Apple> apples = appleCart.getApples();
for (Iterator<Apple> appleIterator = apples.iterator(); appleIterator.hasNext();)
{
   Apple apple = appleIterator.next();
   if ( apple.isYucky() ) {
     appleIterator.remove();
   }
}
+1
source

You can save the list of items to delete, and then delete them after the loop:

List<Apple> apples = appleCart.getApples();
List<Apple> badApples = new ArrayList<Apple>();
for (Apple apple : apples) {
    if (apple.isBad()) {
        badApples.add(apple);
    } else {

    eat(apple);
}

apples.removeAll(badApples);
0
source

All Articles