Is there an accepted best practice in Java for deleting a list element while iterating over the list?

限于喜欢 提交于 2019-12-01 22:15:54

Yes, use an Iterator. Then you could use its remove method.

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

If you're getting a ConcurrentModificationException, you likely have multiple threads.

So the full answer includes both using Iterator.remove() and synchronizing access to the collection.

For example (where lock is synchronized on by all threads that may modify the list):

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

You could keep a list of items to remove and then remove 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);

Since Java 8 you can now do this: apples.removeIf(apple -> apple.equals(this))

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!