List使用remove()方法陷阱 报java.util.ConcurrentModifica异常


场景模拟

在List数组中有Integer类型的数字1~100,此时需要在改数组中筛选出能被10整除的数字(不要new一个数组,需要在原数组的基础上操作)。

直接使用remove()方法 - 错误的

代码演示通过for循环remove()

public static void main(String[] args) {
        //1、数据准备
        List<Integer> list = new ArrayList<>();
        for (int i = 1; i <= 100; i++) {
            list.add(i);
        }
        System.out.println("原先的数组:" + list);

        //2、通过for循环移除数组元素
        for (Integer integer : list) {
            if (integer % 10 != 0){
                list.remove(integer);
            }
        }

        System.out.println("筛选后的数组:" + list);
    }

报错信息:

Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1013)
	at java.base/java.util.ArrayList$Itr.next(ArrayList.java:967)
	at demo.Demo0.main(Demo0.java:22)

使用iterator(迭代器) remove()方法 - 正确的

代码演示迭代器remove()

public static void main(String[] args) {

        //1、数据准备
        ArrayList<Integer> list  =new ArrayList<Integer>();
        for(int i = 1; i<=100; i++ ) {
            list.add(i);
        }
        System.out.println("原先的数组:" + list);

        //2、使用Iterator操作
        Iterator<Integer> iterator = list.iterator();
        while (iterator.hasNext()){
            if (iterator.next() % 10 != 0){
                iterator.remove();
            }
        }
        System.out.println("筛选后的数组:" + list);

    }

结果:

原先的数组:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
筛选后的数组:[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

分类:Java
标签:
文章目录