遍历Collection,避免在循环中删除对象时避免ConcurrentModificationException

若如初见. 提交于 2020-08-10 09:31:17

问题:

We all know you can't do the following because of ConcurrentModificationException : 我们都知道,由于ConcurrentModificationException您无法执行以下操作:

for (Object i : l) {
    if (condition(i)) {
        l.remove(i);
    }
}

But this apparently works sometimes, but not always. 但这显然有时有效,但并非总是如此。 Here's some specific code: 这是一些特定的代码:

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);
}

This, of course, results in: 当然,这导致:

Exception in thread "main" java.util.ConcurrentModificationException

Even though multiple threads aren't doing it. 即使没有多个线程。 Anyway. 无论如何。

What's the best solution to this problem? 解决此问题的最佳方法是什么? How can I remove an item from the collection in a loop without throwing this exception? 如何在不引发此异常的情况下循环从集合中删除项目?

I'm also using an arbitrary Collection here, not necessarily an ArrayList , so you can't rely on get . 我还在这里使用任意Collection ,不一定是ArrayList ,所以您不能依赖get


解决方案:

参考一: https://stackoom.com/question/wFa/遍历Collection-避免在循环中删除对象时避免ConcurrentModificationException
参考二: https://oldbug.net/q/wFa/Iterating-through-a-Collection-avoiding-ConcurrentModificationException-when-removing-objects-in-a-loop
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!