在迭代列表时删除列表元素是否存在Java中公认的最佳实践?

我发现在执行此操作时避免出现ConcurrentModificationException的最佳方法存在冲突的建议:

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

我倾向于使用Iterator代替List并调用其remove方法。

这在这里最有意义吗?

是的,使用迭代器。 然后你可以使用它的remove方法。

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

如果您收到ConcurrentModificationException,则可能有多个线程。

因此,完整的答案包括使用Iterator.remove() 同步对集合的访问。

例如(可以修改列表的所有线程同步锁定 ):

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

您可以保留要删除的项目列表,然后在循环后删除它们:

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