java ConcurrentModificationException异常原理分析

想了解更多数据结构以及算法题,可以关注微信公众号“数据结构和算法”,每天一题为你精彩解答。也可以扫描下面的二维码关注
在这里插入图片描述


java代码通过for循环删除list中的元素的时候,报下面这个错误ConcurrentModificationException,测试代码如下

    public static void main(String[] args) {
        List<String> mList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            mList.add("" + i);
        }
        for (String item : mList) {
            System.out.println(mList.remove(item));
        }
    }

运行结果如下

Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
	at java.util.ArrayList$Itr.next(ArrayList.java:859)

我们来看下list的remove方法,其中有个值是modCount,list调用remove方法的时候modCount会执行加1
在这里插入图片描述
而foreach的背后实现原理其实就是Iterator,我们来看下他的代码,这里只截取其中的一部分
在这里插入图片描述
Iterator类中有一个expectedModCount变量,在Itr的构造函数中被初始化的,他其实就是ArrayList的modCount值,所以foreach一旦执行,expectedModCount就会被初始化,后面就不会在变了。正常情况下Iterator中的expectedModCount和ArrayList中modCount的值是一样的。但我们执行ArrayList的remove方法的时候,ArrayList中的modCount会加1,导致modCount和expectedModCount不再相等。而Iterator中的next方法中有这样一个函数

this.checkForComodification();

我们来看下他的实现

        final void checkForComodification() {
            if (ArrayList.this.modCount != this.expectedModCount) {
                throw new ConcurrentModificationException();
            }
        }

看到没,因为他俩不相等了,所以在这里就会抛异常。那么有没有解决方式呢,当然有的,我们来看下Iterator的remove方法
在这里插入图片描述
他在调用ArrayList的remove方法后,expectedModCount的值也会跟着变,所以这样就不会出现问题了,所以我们可以使用Iterator的remove方法来执行删除操作,代码如下

    public static void main(String[] args) {
        List<String> mList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            mList.add("" + i);
        }
//        for (String item : mList) {
//            System.out.println(mList.remove(item));
//        }
        Iterator<String> iterator = mList.iterator();
        while (iterator.hasNext()) {
            iterator.next();
            iterator.remove();
        }
    }

这样删除就不会报错了


在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

数据结构和算法

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值