如何在集合数据删除时---避免ConcurrentModificationException异常呢?

戚薇 Java经验 发布时间:2023-05-04 22:19:32 阅读数:2465 1
下文笔者讲述避免出现ConcurrentModificationException异常的解决方法分享,如下所示

ConcurrentModificationException异常的演示


public static void main(String[] args) {
    Collection<Integer> l = new Arraylist<>();

    for (int i = 0; i < 10; ++i) {
        l.add(44);
        l.add(55);
        l.add(66);
    }

    for (int i : l) {
        if (i == 55) {
            l.remove(i);
        }
    }

    System.out.println(l);
}

以上代码,会导致异常信息
Exception in thread "main" java.util.ConcurrentModificationException
那么如何避免这类异常呢?下文笔者讲述具体的实现思路
只需使用Iterator.remove() 移除元素
    即可避免此类异常
例:list删除元素的正确写法
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();
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202305/16832100076349.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者