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

需求

在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方法的作用是什么?与线程安全有什么关系?

猜你喜欢

转载自blog.csdn.net/qq_15329947/article/details/86764451
今日推荐