我们都知道你不能这样做:
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.
在Java中,使用foreach循环遍历集合时,对集合调用remove是否合法?例如:
List<String> names = ....
for (String name : names) {
// Do something
names.remove(name).
}
Run Code Online (Sandbox Code Playgroud)
作为附录,删除尚未迭代的项目是否合法?例如,
//Assume that the names list as duplicate entries
List<String> names = ....
for (String name : names) {
// Do something
while (names.remove(name));
}
Run Code Online (Sandbox Code Playgroud)