Java List Remove时要注意的细节

1、如果你是在遍历的时候去remove一个对象

  for(int i = 0, length = list.size(); i<length; i++){}

    这种遍历需要每次remove时,对i--,也要对length--,或者i<list.size()

  for(Object o : list){}

    这种遍历时,remove也是有问题的,需要去看下class文件的具体实现,待研究

       for(Iterator<T> it = list.iterator(); it.hasNext();){}

      这种遍历时,remove也是有问题的,需要去看下源码实现(AbstractList和remove方法)

 

2、remove(Object o),注意Object的equals实现

public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

  需要注意源码中是用equals去判断的,如果你的Object重写了equals方法,就需要注意了。

       

转载于:https://www.cnblogs.com/mxm985/p/7092729.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值