【无标题】Java的remove陷阱

文章分析了Java中ArrayList的remove方法在迭代器中的行为,解释了为什么第一段代码能正常运行,而第二段代码由于modCount检查导致异常。关键在于迭代器的使用和ArrayList内部机制。
摘要由CSDN通过智能技术生成
List<Integer>arraylist=new ArrayList<>(Arrays.asList(new Integer[]{1,2,3,4,5,6}));
        for(Integer e:arraylist){
            if(5==e){
                System.out.println("here");
                arraylist.remove(e);
            }
        }
        System.out.println(arraylist);
List<Integer>arraylist=new ArrayList<>(Arrays.asList(new Integer[]{1,2,3,4,5,6}));
        for(Integer e:arraylist){
            if(4==e){
                System.out.println("here");
                arraylist.remove(e);
            }
        }
        System.out.println(arraylist);

看上面的两段代码,为什么同样的形式,第一段能运行、而第二段运行不了呢。
先来解释下第二段为什么运行不了
找到反编译结果如下

List<Integer> arraylist = new ArrayList(Arrays.asList(1, 2, 3, 4, 5, 6));
        Iterator var2 = arraylist.iterator();

        while(var2.hasNext()) {
            Integer e = (Integer)var2.next();
            if (4 == e) {
                System.out.println("here");
                arraylist.remove(e);
            }
        }

        System.out.println(arraylist);

可以看到,调用了ArrayList的内部类的hasNext、next方法(自行看源码,ArrayList内部有类Itr实现了Iterator接口),
源代码调用了ArrayList的remove方法、而不是Ite的remove方法,remove方法内使modCount加1,看反编译地方,当调用next方法时会核对modCount和expectedModCount是否一致,否则并分修改异常,问题出在这里。但是如果打印出来发现、remove是生效了的

那么为什么第一段代码可以正常运行呢,其实这是“凑巧了”。当remove的元素是倒数第二个时,不会发生此异常。
当删除5时,remove掉5,remove方法中size小了一个,进入下一次循环,注意,此时cursor(只在next方法中修改)在第五个位置,hasnext方法源码return cursor!=size
此时发现不满足条件,不会进入循环,自然不会调用next方法,自然没有异常。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值