在迭代列表时删除列表元素是否存在Java中公认的最佳实践?
问题描述:
我发现在执行此操作时避免 ConcurrentModificationException 的最佳方法存在冲突的建议:
I'm finding conflicting advice over the best way to avoid a ConcurrentModificationException while doing this:
List<Apple> Apples = appleCart.getApples();
for (Apple apple : Apples)
{
delete(apple);
}
我倾向于使用 Iterator 代替 List 并调用其 remove 方法。
I'm leaning towards using an Iterator in place of a List and calling its remove method.
这在这里最有意义吗?
答
是的,使用迭代器。然后你可以使用它的删除方法。
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();
}
}
}