相关疑难解决方法(0)

迭代集合,在循环中删除对象时避免使用ConcurrentModificationException

我们都知道你不能这样做:

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 iteration collections

1158
推荐指数
12
解决办法
46万
查看次数

在Java中调用foreach循环中的remove

在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)

java foreach iterator loops

575
推荐指数
7
解决办法
41万
查看次数

标签 统计

java ×2

collections ×1

foreach ×1

iteration ×1

iterator ×1

loops ×1