遍历Collection,避免在循环中删除对象时避免ConcurrentModificationException?| Java Debug 笔记

166 阅读1分钟

本文正在参加「Java主题月 - Java Debug笔记活动」,详情查看活动链接

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

我们都知道您由于以下原因而无法执行以下操作ConcurrentModificationException:

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

但这显然有时会奏效,但并非总是如此。这是一些特定的代码:

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

当然,这会导致:

Exception in thread "main" java.util.ConcurrentModificationException

即使没有多个线程。反正。

解决此问题的最佳方法是什么?如何在不引发此异常的情况下从循环中删除集合中的项目?

我还在Collection这里使用任意值,不一定是an ArrayList,因此您不能依赖get。

高分回答:

很多的知识点,真的需要写出来才会掌握!!! \color{purple}很多的知识点,真的需要写出来才会掌握!!!{~}

Iterator.remove() 是安全的,您可以像这样使用它:

List<String> list = new ArrayList<>();

// This is a clever way to create the iterator and call iterator.hasNext() like
// you would do in a while-loop. It would be the same as doing:
//     Iterator<String> iterator = list.iterator();
//     while (iterator.hasNext()) {
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
    String string = iterator.next();
    if (string.isEmpty()) {
        // Remove the current element from the iterator and the list.
        iterator.remove();
    }
}

注意,这Iterator.remove()是在迭代过程中修改集合的唯一安全方法。如果在迭代进行过程中以任何其他方式修改了基础集合,则行为未指定。

文章翻译自 yl2gl72eozkinivz3vc6swkesy-ac4c6men2g7xr2a-translate.translate.goog/questions/2…

作者建议:回答满分,这个异常作者也遇见过

欢迎关注我的专栏StackOverFlow,我会筛选优质的问答,面试常考!!! \color{red}欢迎关注我的专栏StackOverFlow,我会筛选优质的问答,面试常考!!!{~}

有最新、优雅的实现方式,我也会在文末写出我对本问答的见解 \color{red}有最新、优雅的实现方式,我也会在文末写出我对本问答的见解{~}

真心感谢帅逼靓女们能看到这里,如果这个文章写得还不错,觉得有点东西的话

求点赞👍 求关注❤️ 求分享👥 对8块腹肌的我来说真的 非常有用!!!

如果本篇博客有任何错误,请批评指教,不胜感激 !❤️❤️❤️❤️