Java ArrayList异常-ConcurrentModificationException

前言

在操作List集合的时候,习惯用for each循环操作。这次项目中根据业务逻辑需要删除符合条件的元素,元素删除后,继续next操作,抛出了ConcurrentModificationException异常。下面,重现异常,看看异常是怎么发生的,怎么避免。

测试代码

public class ConcurrentModificationExceptionList {  
    public static void main(String[] args) {
        List<Integer> list1 = new ArrayList<>();
        list1.add(1);
        list1.add(2);
        list1.add(3);
        list1.add(4);
        for (Integer integer : list1) {
            if (integer == 1) {
                list1.remove(integer);
            }
        }
    }
}

异常的发生

ConcurrentModificationException异常是在这里抛出的。当modCount != expectedModCount为true的时候抛出。

这里写图片描述

这里写图片描述

原因

上述异常为什么会发生,来看一下源码中的删除动作。

这里写图片描述

这里写图片描述

在执行删除动作前modCount自加1。在下个元素做checkForComodification的时候异常就抛出了。

这里写图片描述

异常的解决

这里写图片描述

查看源码,modCount是在ArrayList的父类AbstractList中定义的,modCount记录list被修改的次数。在iterator和实现iterator的list中,进行next(),remove()、previous、set、add操作时,modCount的值被意外改变,将抛出异常ConcurrentModificationException。关于异常的解决,网上也有很多的方法,参考文末。

既然异常是在iterator和实现iterator的list中发生的,那不使用for each操作,采用for in操作就能避免异常的发生。

代码验证一下

        for (int i = 0; i < list1.size(); i++) {
            if (list1.get(i)==1){
                list1.remove(i);
                i--;//指向删除前的上一个元素
            }
        }

这里写图片描述

看一下源码:

这里写图片描述

源码中是没有做checkForComodification检查的,也不会发生异常。

参考

Java ConcurrentModificationException异常原因和解决方法
集合迭代时对集合进行修改抛ConcurrentModificationException原因的深究以及解决方案
Java ConcurrentModificationException 异常分析与解决方案

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值