踩坑记录--list.remove()方法陷阱

一、首先说正确的方式

1、让索引同步调整

        for (int i = 0; i < list.size(); i++) {
            Apple apple = list.get(i);
            if(apple.getWeight()==23){
                list.remove(i--);
            }
        }

2、倒序遍历List删除元素

        for (int i = list.size() - 1; i >= 0; i--) {
            Apple apple = list.get(i);
            if (apple.getWeight() == 23) {
                list.remove(i);
            }
        }

3、Iterator.remove() 方法会在删除当前迭代对象的同时,会保留原来元素的索引,建议使用此方式。

        Iterator<Apple> iterator = list.iterator();
        while (iterator.hasNext()) {
            Apple apple = iterator.next();
            if (apple.getWeight() == 23) {
                iterator.remove();
            }
        }

二、错误的删除方式

1、正序遍历

        for (int i = 0; i < list.size(); i++) {
            Apple apple = list.get(i);
            if(apple.getWeight()==23){
                list.remove(i);
            }
        }

2、迭代遍历,用list.remove(i)方法删除元素,抛出异常:java.util.ConcurrentModificationException

        Iterator<Apple> iterator = list.iterator();
        while (iterator.hasNext()) {
            Apple apple = iterator.next();
            if (apple.getWeight() == 23) {
                list.remove(apple);
            }
        }

3、forech删除,抛出异常:java.util.ConcurrentModificationException

        for (Apple apple : list) {
            if (apple.getWeight() == 23) {
                list.remove(apple);
            }
        }

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ljt-tiger

thanks

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值