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方法,就需要注意了。

       


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM