ArrayList源码解析 删除元素

首先我们来看下代码:

public static void main(String[] args) {
        List list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(i + "");
        }
        list.remove(5);
        list.remove("8");
        System.out.println(list.size());
    }

在list.remove(5)时debug一下,可以看到初始化(循环)结束时的list的情况:


image.png

在我们运行到list.remove(5)的时候再看一下:


image.png

我们看到原来下标为5的字符串被移除了。
好吧那我们定位到remove()方法的实现来看看:
/**
     * Removes the element at the specified position in this list.
     * Shifts any subsequent elements to the left (subtracts one from their
     * indices).
     *
     * @param index the index of the element to be removed
     * @return the element that was removed from the list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    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;
    }

首先注释已经写的很明白了,这个方法就是移除ArrayList某个确定位置的元素,并且把这个位置随后的元素向左移一位。之后来看具体实现:
rangeCheck()的实现:

/**
     * Checks if the given index is in range.  If not, throws an appropriate
     * runtime exception.  This method does *not* check if the index is
     * negative: It is always used immediately prior to an array access,
     * which throws an ArrayIndexOutOfBoundsException if index is negative.
     */
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

通过注释和代码很显然这个方法就是防止索引大于ArrayList的元素数的。
modCount++我们先不看(因为我也不太明白modCount这个属性是做啥的,反正就是维持一个记录数组变化次数的变量)
接下来我们看elemData()方法

// Positional Access Operations

    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

这个代码也非常简单就是返回ArrayList制定位置的元素嘛。
然后就是如果指定位置后面还有元素就把后面的元素都往左移(复制过来)一位,覆盖掉原来的位置并把ArrayList内的数组的最后一位置为null,ArrayList的容量减一。
我来画张图来演示一下:
没有运行remove(5)时的图:


image.png

(这个图画的有点错误因为我创建出来的ArrayList里面的元素应该是字符串类型的但是图了个方便就直接写成数字了)

然后执行remove(5)的过程是:


image.png
image.png

我们来看一下代码到这里的执行结果:


image.png

和我们预想的一样。
代码继续执行,执行到了remove("8");
好吧我们来看看这个方法的代码:

/**
     * Removes the first occurrence of the specified element from this list,
     * if it is present.  If the list does not contain the element, it is
     * unchanged.  More formally, removes the element with the lowest index
     * i such that
     * (o==null ? get(i)==null : o.equals(get(i)))
     * (if such an element exists).  Returns true if this list
     * contained the specified element (or equivalently, if this list
     * changed as a result of the call).
     *
     * @param o element to be removed from this list, if present
     * @return true if this list contained the specified element
     */
    public boolean remove(Object o) {
        if (o == null) {//如果要删除的元素为null
            for (int index = 0; index < size; index++)
            //遍历数组中的元素如果找到这个需要删除的元素,执行fastRemove(index)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;//删除成功返回true
                }
        } else {//要删除的元素不是null
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {//用equals()方法做比较如果找到相同的元素运行
                                                   //fastRemove(index)                  
                    fastRemove(index);
                    return true;//删除成功返回true
                }
        }
        //返回失败返回false
        return false;
    }

我们再来看下fastRemove()方法

/*
     * Private remove method that skips bounds checking and does not
     * return the value removed.
     */
    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
    }

这个方法简直和我们执行的remove(5)简直一毛一样
我们最后再来看看下执行结果


image.png

你可能感兴趣的:(ArrayList源码解析 删除元素)