栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

foreach遍历容器出现ConcurrentModificationException()

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

foreach遍历容器出现ConcurrentModificationException()

问题描述

例如:用foreach遍历容器时,并同时对容器进行修改操作,会出现ConcurrentModificationException()异常

public class Ttest {
    Vector vectors=new Vector();
    public Ttest(){
        vectors.add("a");
        vectors.add("b");
        vectors.add("c");
        vectors.add("d");
        vectors.add("e");
        vectors.add("f");
    }
    public static void main(String[] args) {
        Ttest ttest=new Ttest();
        for (String vector : ttest.vectors) {
            if (vector.equals("b")){
                System.out.println("删除"+vector);
                ttest.vectors.remove(vector);
            }else {
                System.out.println(vector);
            }

        }
//        for (int i=0;i
//            String vector=ttest.vectors.get(i);
//            if (vector.equals("b")){
//                System.out.println("删除"+vector);
//                ttest.vectors.remove(vector);
//            }else {
//                System.out.println(vector);
//            }
//        }
    }
}

打印结果

a
删除b
Exception in thread "main" java.util.ConcurrentModificationException at java.util.Vector$Itr.checkForComodification(Vector.java:1212) at java.util.Vector$Itr.next(Vector.java:1165) at com.example.tankgame.thread.Ttest.main(Ttest.java:24)


原因分析:

用foreach进行容器遍历时,其本质还是用的迭代器遍历容器
迭代器初始化是在Itr()中,会有int expectedModCount = modCount;
每进行一次遍历都会checkForComodification() 去检查expectedModCount 与modCount是否相等
而在遍历中进行修改(删除/新增)会使得modCount++; 此时checkForComodification()去执行发现expectedModCount != modCount 就会抛出异常ConcurrentModificationException()

遍历调用到的方法(force step into下跟 )
for (String vector : vectors)->iterator()->new Itr()
->int expectedModCount = modCount;
->hasNext()
->next() ->checkForComodification
->elementData

借鉴了该篇文章,解决了我的困惑,十分感谢

https://blog.csdn.net/qq_46312987/article/details/122383715

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/933062.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号