集合遍历修改ConcurrentModificationException异常

0. 栗子

 下述栗子会报ConcurrentModificationException异常
`
 【原因】:集合迭代遍历中对集合结构修改(添加/移除),modCount值会加1,而预期值expectedModCount不变,便会报异常

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("111");
        list.add("222");
        list.add("333");

        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String ele = iterator.next();
            if (StringUtils.equals(ele, "111")) {
//                list.add("444");
                list.remove("111");

            }
        }
    }
1. 原因解析:

 调用list.iterator(); 生成迭代器对象,该对象是ArrayList的内部类

  • cursor表示下一个要访问的元素下标,初始值为0
  • modCount表示集合结构修改的计数器;
  • expectedModCount是于其的计数器值,在list.iterator();创建时初始化值为modCount

在这里插入图片描述

1.1. 集合遍历remove非倒数第二个元素,会报异常
      /**
         *  本例集合add了三个元素,size=3;modCount=3;cursor默认0
         *	hasNext()通过比较cursor != size;来判断是否还有下一个元素
         *
         *  |-------|-------|-------|
         *  0       1       2       3
         *  cursor                  size    第一次循环判断通过,next()方法中判断modCount != expectedModCount,不成立不报异常,cursor加1
         *                                  list.remove("111");后size减1;modCount加1,而expectedModCount不变
         *          cursor  size            第二次循环判断通过,next()方法中判断modCount != expectedModCount 成立,报异常
         */
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String ele = iterator.next();
            if (StringUtils.equals(ele, "111")) {
//                list.add("444");
                list.remove("111");

            }
        }

 第一次循环判断通过,next()方法中判断modCount != expectedModCount,不成立不报异常,cursor加1

        public boolean hasNext() {
            return cursor != size;
        }

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }
        
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }

 list.remove(“111”);后size减1;modCount加1,而expectedModCount不变

	// 这是ArrayList的方法
    private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work
    }

 第二次循环判断通过,next()方法中判断modCount != expectedModCount 成立,报异常

1.2. 集合遍历remove倒数第二个元素,不会报异常
        /**
         *  集合遍历remove倒数第二个元素,不会报异常
         *
         *  |-------|-------|-------|
         *  0       1       2       3
         *  cursor                  size    第一次循环判断通过,next()方法中判断modCount != expectedModCount,不成立不报异常,cursor加1
         *          cursor          size    第二次循环判断通过,next()方法中判断modCount != expectedModCount,不成立不报异常
         *                                  list.remove("222");后size减1;
         *                  cursor
         *                  size            第三次循环判断不成立,直接退出,不会在next()方法中判断modCount != expectedModCount,所以不会报异常
         */
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String ele = iterator.next();
            if (StringUtils.equals(ele, "222")) {
                list.remove("222");
            }
        }
    }

 【小结】:集合迭代遍历中对集合结构修改(添加/移除),modCount值会加1,而预期值expectedModCount不变,便会报异常

2. 其他遍历写法异常情况:

 增强for循环遍历(foreach遍历),本质是隐式的iterator,和上述iterator情况一样

        for (String ele : list) {
            if (StringUtils.equals(ele, "111")) {
//                list.add("444");
                list.remove("111");

            }
        }

 普通for循环写法:这种方式remove不会报异常,因为循环过程就不会判断modCount != expectedModCount

        for (int i = 0; i < list.size(); i++) {
            if (StringUtils.equals(list.get(i), "111")) {
                list.remove("111");
            }
        }

 这种写法有个弊端,若初始集合为[111, 111, 222, 333],遍历remove后集合为[111, 222, 333]; 而迭代遍历111的所有元素都会移除

3. 推荐写法:

 如果要在遍历中修改,推荐用迭代器的内部remove方法,而不是实现类的remove方法

        /**
         * 迭代器的remove后会将期待值重新赋值expectedModCount = modCount;所以不会报异常
         * 熟悉lambda表达式的还可以简化写法list.removeIf(ele -> StringUtils.equals(ele, "111"));
         */
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String ele = iterator.next();
            if (StringUtils.equals(ele, "111")) {
                iterator.remove(); // 迭代器的remove方法

            }
        }

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值