foreach遍历集合进行增删,导致ConcurrentModificationException异常

发布于:2022-08-08 ⋅ 阅读:(558) ⋅ 点赞:(0)

foreach遍历list集合进行增删,导致ConcurrentModificationException异常

以ArrayList集合为例

ArrayList<String> list = new ArrayList<>();
list.add("aa");
list.add("bb");
list.add("cc");
for (String str : list) {
    if (str.equals("aa")){
        list.remove("bb");
    }
    System.out.println(str);
}

这时会出现并发修改异常 :

image-20220807172004411

出现ConcurrentModificationException异常的原因:

1、ArrayList继承了AbstractList,

image-20220807172627892

AbstractList存在成员变量modCount,

image-20220807172833999

每当对ArrayList集合进行修改时,modCount就会加1,以ArrayList集合里的remove()方法为例

image-20220807173158998

2、foreach的循环:底层采用的是迭代器Iterator(Itr,这个类是ArrayLIst实现的内部类),每次循环都会调用.next()访问下一个元素。

在迭代器初始化时,expectedModCount == modCount

在用.next()访问下一个元素,如果这时,你对集合进行remove()操作时,modCount会加1

那么modCount 就会不等于 expectedModCount ,从而抛出ConcurrentModificationException异常

image-20220807174840950

但使用迭代器iterator进行遍历remove删除,却不会报错

代码如下

ArrayList<String> list = new ArrayList<>();
list.add("aa");
list.add("bb");
list.add("cc");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()){
    if (iterator.equals("aa")){
        iterator.remove();
    }
}
System.out.println(list);
//成功执行 [bb, cc]

因为iterator里的方法remove(),对expectedModCount赋值为最新的modCount值,所以能够正常执行

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到