java list.remove移除失败

 1. resultList.remove(i) 移除失败说明

  当i为Integer类型时,通过观察源码发现当找不到该类型时就会自动去找Object类型,即remove(object),因为集合中不存在对象类型的值,所以会造成失败。

2. 解决方案

  resultList.remove(i.intValue())

3. remove源码

 

 public E remove(int index) {
        rangeCheck(index);

        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }
 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;
    }
private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work
    }

 

posted @ 2018-01-02 14:48  春风十里的情  阅读(1634)  评论(0编辑  收藏  举报