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

       

posted @ 2017-06-29 09:29  mxm985  阅读(2063)  评论(0编辑  收藏  举报