ArrayList源码解读之remove(Object o)和remve(int index)

样例

/**
     * 2.测试remove和fastRemove区别
     * E remove(int index)
     */
    public static void test2(){
        ArrayList list1 = new ArrayList();
        list1.add(1);
        list1.add(2);
        list1.add(5);
        list1.add(6);
        list1.add(null);
        list1.add(7);

        list1.remove(Integer.valueOf(6));
        list1.remove(Integer.valueOf(2));
        list1.remove(null);
        list1.remove(1);
    }

remove(Object o)

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;
    }

fastRemove(index)私有方法

private void fastRemove(int index) {
        modCount++;//记录对象list被修改次数
        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
    }

System.arraycopy()方法

public static native void arraycopy(Object src,  int  srcPos,Object dest, int destPos,int length);

remove(int index)

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;
    }

System.arraycopy()方法

public static native void arraycopy(Object src,  int  srcPos,Object dest, int destPos,int length);

remove(Object o)数组结构图解

ArrayList源码解读之remove(Object o)和remve(int index)

相关文章:

  • 2021-05-11
  • 2022-12-23
  • 2021-07-07
  • 2021-07-08
  • 2022-02-06
  • 2021-10-21
  • 2021-10-28
  • 2021-05-23
猜你喜欢
  • 2021-06-07
  • 2022-12-23
  • 2021-06-30
  • 2021-05-04
  • 2021-07-16
  • 2021-06-01
  • 2022-12-23
相关资源
相似解决方案