ForEach遍历ArrayList并删除其中元素时抛出异常:java.util.ConcurrentModificationException以及解决办法

1 篇文章 0 订阅

需求

在ArrayList中存入整数1 - 5,移除其中小于4的元素。

代码实现

package com.cloudpig.bootredis;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class BootRedisApplicationTests {

    private List<Integer> getNums() {
        List<Integer> nums = new ArrayList<>();
        nums.add(1);
        nums.add(2);
        nums.add(3);
        nums.add(4);
        nums.add(5);
        return nums;
    }

    /**
     * 方法一:使用foreach循环遍历ArrayList,从其中移除符合条件的元素。
     * 会报错:java.util.ConcurrentModificationException
     */
    @Test
    public void removeElementsFromListByForEach() {
        List<Integer> nums = getNums();
        for (Integer num : nums) {
            if (num < 4) {
                nums.remove(num);
            }
        }
        System.out.println(nums);
    }

    /**
     * 方法二:使用foreach循环遍历ArrayList,将符合条件的元素放入新的ArrayList。
     * 循环结束后,使用removeAll方法从原集合中删除新集合。
     * 可以得到正确结果:[4, 5]
     */
    @Test
    public void removeListFromList() {
        List<Integer> nums = getNums();
        List<Integer> nums2Remove = new ArrayList<>();
        for (Integer num : nums) {
            if (num < 4) {
                nums2Remove.add(num);
            }
        }
        nums.removeAll(nums2Remove);
        System.out.println(nums);
    }

    /**
     * 方法三:获取ArrayList的迭代器,调用iterator.remove()移除符合条件的元素。
     * 可以得到正确结果:[4, 5]
     */
    @Test
    public void removeElementsFromListByIterator() {
        List<Integer> nums = getNums();
        Iterator<Integer> iterator = nums.iterator();
        while (iterator.hasNext()) {
            Integer next = iterator.next();
            if (next < 4) {
                iterator.remove();
            }
        }
        System.out.println(nums);
    }


}

方法一会导致报错:

java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
	at java.util.ArrayList$Itr.next(ArrayList.java:859)

这是由于ArrayList的私有内部类Itr中的checkForComodification()检查出ArrayList的成员变量modCount和Itr的成员变量expectedModCount的值不一致造成的。

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

方法二和方法三可以用以解决此问题。

抛砖引玉

1、将上述需求改为“在ArrayList中存入整数1 - 5,移除其中大于3的元素”,方法一还会报错吗?
2、将上述代码中List的实现类改为LinkedList,会怎样?ArrayList和LinkedList的区别。
3、checkForComodification方法的作用是什么?与线程安全有什么关系?

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值