如何在没有ConcurrentModificationException的情况下使用for-each循环迭代时修改Collection?

aps*_*aps 22 java collections concurrentmodification

如果我在使用for-each循环迭代它时修改Collection,它会给出ConcurrentModificationException.有没有解决方法?

mre*_*mre 38

使用Iterator#remove.

这是在迭代期间修改集合的唯一安全方法.有关更多信息,请参阅"集合接口"教程.

如果您还需要在迭代时添加元素,请使用ListIterator.


jzd*_*jzd 11

一个解决方法是保存更改并在循环后添加/删除它们.

例如:

List<Item> toRemove = new LinkedList<Item>();

for(Item it:items){
    if(remove){
        toRemove.add(it);
    }
}
items.removeAll(toRemove);
Run Code Online (Sandbox Code Playgroud)