我们都知道你不能这样做:
for (Object i : l) {
if (condition(i)) {
l.remove(i);
}
}
Run Code Online (Sandbox Code Playgroud)
ConcurrentModificationException
等等......这显然有时起作用,但并非总是如此.这是一些特定的代码:
public static void main(String[] args) {
Collection<Integer> l = new ArrayList<>();
for (int i = 0; i < 10; ++i) {
l.add(4);
l.add(5);
l.add(6);
}
for (int i : l) {
if (i == 5) {
l.remove(i);
}
}
System.out.println(l);
}
Run Code Online (Sandbox Code Playgroud)
当然,这会导致:
Exception in thread "main" java.util.ConcurrentModificationException
Run Code Online (Sandbox Code Playgroud)
...即使多线程没有这样做......无论如何.
什么是这个问题的最佳解决方案?如何在循环中从集合中删除项而不抛出此异常?
我也在Collection
这里使用任意,不一定是ArrayList
,所以你不能依赖get
.