ArrayList源码解析 删除元素

首先我们来看下代码:

public static void main(String[] args) {
        List<String> 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
     * <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
     * (if such an element exists).  Returns <tt>true</tt> 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 <tt>true</tt> 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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 又是半夜爬起来,写晚安笔记。 我一直在犹豫要不要给朋友圈做一次“大清理”。这个动作不是简单地加个机器人做一个查找谁...
    茉莉大大阅读 108评论 0 0
  • 1
    A旗开得胜阅读 58评论 0 0
  • 参考于:Android之Dialog详解 7种形式的Android Dialog使用举例 (一)概述 andro...
    CokeNello阅读 2,871评论 1 13
  • 第89首现代诗,下班后看着月亮写下的,茉莉写于1122,耗时10分,配图为茉莉手绘。 他说,已经不记得 千百年前,...
    茉莉的小茶馆阅读 244评论 3 5
  • 听最轻曼最忧伤的民谣,看最狂躁最暴戾的金属现场,写最露骨最直白的文字,读最淫荡最文艺的小黄书。 谁说中年男人就得天...
    逡巡者阅读 479评论 1 2