ArrayList部分源码阅读笔记

前言

本文的源码是基于JDK1.8。本文通过对构造方法以及增删改查主要方法进行分析,来学习ArrayList。难点主要是add方法和remove方法。

疑问

ArrayList默认容量是多少。
ArrayList扩容多少倍。
remove(Object o)和remove(int index)的区别。
当Integer i =1;remove(i)调用的是哪一个方法。
解答放在文章末尾。

两个主要的属性

elementData:
elementData,即内部维护的一个Object类型的数组;
size:
size,the number of elements it contains.
即元素的个数,而非容器的容量。因此,size <= elementData.length

构造方法

构造方法中用到的三个属性:

    private static final int DEFAULT_CAPACITY = 10;

    private static final Object[] EMPTY_ELEMENTDATA = {};

    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

构造方法有3个:

    //无参构造函数,将elementData数组设置为空数组,注意是空数组而不是null
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    //初始化ArrayList并指定初始容量
    public ArrayList(int initialCapacity) {
        //创建指定长度的数组并将地址赋给elementData
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } 
        //若为0,则将elementData数组设置为空数组
        else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } 
        //若该值小于0,抛出异常
        else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    //初始化ArrayList,并且其形参是一个Collection容器
    public ArrayList(Collection<? extends E> c) {
        //获取一个全新模板的数组
        elementData = c.toArray();  //重点
        //如果数组中元素个数不为0
        if ((size = elementData.length) != 0) {
            // c.toArray方法返回的不一样是Object[]类型
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        }
        //如果数组中元素个数为0 
        else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

    /**
     * 复制该数组并返回该数组,该数组是安全的因为这个返回的数组是新的,没有任何其他引用
     * Returns an array containing all of the elements in this list
     * in proper sequence (from first to last element).
     *
     * <p>The returned array will be "safe" in that no references to it are
     * maintained by this list.  (In other words, this method must allocate
     * a new array).  The caller is thus free to modify the returned array.
     *
     * 该方法是数组类和集合类api的一个桥梁。
     * <p>This method acts as bridge between array-based and collection-based
     * APIs.
     *
     * @return an array containing all of the elements in this list in
     *         proper sequence
     */
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

增删改查

用到的属性MAX_ARRAY_SIZE

private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

add方法有多个,
如add(E e)是在尾部插入新元素,
如add(int index, E element)是在指定位置插入新元素,
如addAll(Collection

    /**
     * Appends the specified element to the end of this list.
     * 将指定元素增加到list的尾部。
     *
     * @param e element to be appended to this list
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        //确认容量,保证能再插入多1个元素
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        //在末尾插入新元素
        elementData[size++] = e;
        return true;
    }

    //确认容量,可能会扩容
    private void ensureCapacityInternal(int minCapacity) {
        //如果elementData为空数组,则设置其容量为10
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        ensureExplicitCapacity(minCapacity);
    }

    //判断是否需要扩容
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;
        //minCapacity的值为当前元素个数+新增元素个数(可能大于1)
        //如果minCapacity大于当前容器的容量,则执行扩容操作
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    //扩容方法
    private void grow(int minCapacity) {
        int oldCapacity = elementData.length;
        //newCapacity表示新的容量值,将其设置为oldCapacity的1.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        //若扩容后的值还是不够大,则以minCapacity为新的容量值
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        //扩容后的容量大于数组最大长度
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        //将旧数组的元素复制到新数组中并新数组引用赋给elementData
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    //设置最大容量值
    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        //如果minCapacity大于MAX_ARRAY_SIZE,则将容量设置为最大值
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

add(E e)方法看懂的话,add(int index, E element)就很容易了。

    /**
     * 从指定位置起往右的元素都要右移一位,然后将指定元素插入到容器的该位置
     * Inserts the specified element at the specified position in this
     * list. Shifts the element currently at that position (if any) and
     * any subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        //先检查该index是否正常
        rangeCheckForAdd(index);
        //确认容量,可能会扩容
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        //实现的效果就是将index位置往后的元素后移1位,空出下标为index的位置
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        //将新元素放入到index指向的位置
        elementData[index] = element;
        //size存储的是元素个数,加一
        size++;
    }
    //判断该index是否正常
    private void rangeCheckForAdd(int index) {
        //如果index的值不合法则抛出异常
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * 将数组的某一段复制到另一个数组的某个位置
     * @param      src      the source array.
     * @param      srcPos   starting position in the source array.
     * @param      dest     the destination array.
     * @param      destPos  starting position in the destination data.
     * @param      length   the number of array elements to be copied.
     */
    public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

remove方法也有几个。
如remove(int index)是移除指定位置的元素,
如remove(Object o)是移除指定的元素,
如clear()是移除所有元素,
如removeAll(Collection

    /**
     * 移除指定位置的元素,并将该位置往后的元素左移一位
     * 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) {
        //先检查该index是否合法,不合法则抛出异常
        rangeCheck(index);

        modCount++;
        //取出要删除的值,最后返回它
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        //若numMoved为0,则说明index指向的是最后一个元素,则无需移动其他元素
        //否则,将index往后的元素左移一位,通过System.arraycopy方法实现
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        //size减一,并释放该元素,注意不能写成size--
        elementData[--size] = null; // clear to let GC do its work
        //返回被删除的元素
        return oldValue;
    }

    //判断index是否大于等于当前元素个数
    private void rangeCheck(int index) {
        //是的话抛出异常
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

remove(Object o)方法:

    /**
     * 移除容器中第一个出现的指定元素,如果不存在则不变动
     * 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. 
     *
     * @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) {
        //指定元素是否为null,其遍历判断时的方式不同,因此有if else
        //如果指定的元素为null
        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;
                }
        }
        //若找不到符合要求的元素,则返回false
        return false;
    }

    /*
     * 该方法忽略了边界检查且没有返回被删除的值。
     * 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);
        //size减一并释放这个被删除的元素
        elementData[--size] = null; // clear to let GC do its work
    }

clear()方法:

    /**
     * 移除容器中所有的元素
     * Removes all of the elements from this list.  The list will
     * be empty after this call returns.
     */
    public void clear() {
        modCount++;

        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }

removeAll方法:

    /**
     * 移除批量元素
     * Removes from this list all of its elements that are contained in the
     * specified collection.
     */
    public boolean removeAll(Collection<?> c) {
        //若c为null,则抛出异常
        Objects.requireNonNull(c);
        //否则调用batchRemove方法并返回操作是否成功
        return batchRemove(c, false);
    }

    /*
     * @param complement 补足,补角,补体
     */
    private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        //r表示read,w表示write
        int r = 0, w = 0;
        boolean modified = false;
        try {
            //遍历元素,实现的效果是,将需要保留的元素放到[0,w)中
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement)
                    elementData[w++] = elementData[r];
        } finally {
            // 翻译过来是:保持与AbstractCollection的行为兼容性
            // Preserve behavioral compatibility with AbstractCollection,
            // even if c.contains() throws.
            // 当还是不懂下面第一个if的意义在哪里
            if (r != size) {
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            //如果w != size,说明并非保留了所有的元素
            if (w != size) {
                // clear to let GC do its work
                //[0,w)这部分是保留的,因此,要释放后面的元素
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }

前面介绍的方法都是移除指定的一个或多个或者全部元素,而retainAll方法移除的是形参容器中没有的元素,即保留形参容器中有的元素。batchRemove方法看懂了,该方法也很容易了。
retainAll方法:

    /**
     * 移除容器的一些元素,移除哪些元素呢,移除容器c中不包含的元素。
     * Retains only the elements in this list that are contained in the
     * specified collection.  In other words, removes from this list all
     * of its elements that are not contained in the specified collection.
     */
    public boolean retainAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }

修改方法就一个。
set(int index, E element)方法:

    /**
     * 用指定的元素替代容器中指定位置的元素
     * Replaces the element at the specified position in this list with
     * the specified element.
     *
     * @param index index of the element to replace
     * @param element element to be stored at the specified position
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E set(int index, E element) {
        //先检查index是否合法
        rangeCheck(index);

        //取出将被替代的元素
        E oldValue = elementData(index);
        //用指定元素替代旧的元素
        elementData[index] = element;
        //返回被替代的值
        return oldValue;
    }

查找相关的方法。

get方法:

    /**
     * 返回指定位置的元素
     * Returns the element at the specified position in this list.
     *
     * @param  index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {
        //先检查index是否合法
        rangeCheck(index);
        //返回指定该位置的元素
        return elementData(index);
    }

contains方法:

    /**
     * Returns <tt>true</tt> if this list contains the specified element.
     *
     * @param o element whose presence in this list is to be tested
     * @return <tt>true</tt> if this list contains the specified element
     */
    public boolean contains(Object o) {
        //通过利用indexOf方法的返回值来判断
        return indexOf(o) >= 0;
    }

    /**
     * 返回指定元素在容器中第一次出现的下标,若不存在则返回-1。
     * 该方法和remove(Object o)很像。
     * Returns the index of the first occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     */
    public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

    /**
     * 返回指定元素在容器中最后出现的下标,若不存在则返回-1。
     * 类似indexOf方法,从后往前遍历即可。
     */
    public int lastIndexOf(Object o) {
        if (o == null) {
            for (int i = size-1; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = size-1; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

isEmpty方法:

    /**
     * Returns <tt>true</tt> if this list contains no elements.
     */
    public boolean isEmpty() {
        return size == 0;
    }

扩容和缩容

扩容方法就是add方法中出现的grow方法(前面已介绍)。

而缩容方法指的是trimToSize方法:

    /**
     * 将容器的容量缩小到当前元素个数。
     * Trims the capacity of this <tt>ArrayList</tt> instance to be the
     * list's current size.  An application can use this operation to minimize
     * the storage of an <tt>ArrayList</tt> instance.
     */
    public void trimToSize() {
        modCount++;
        //只有在元素个数小于容器容量时才考虑缩容
        if (size < elementData.length) { 
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }

解答

1.ArrayList默认容量

    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
    private void ensureCapacityInternal(int minCapacity) {
        //if语句,只有在第一次被调用的时候才有可能成立。
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
}

当调用无参构造函数时,容器的elementData指向的是一个空数组DEFAULTCAPACITY_EMPTY_ELEMENTDATA。当调用add方法时才会初始化容器的容量。如ensureCapacityInternal方法中所写,如果elementData指向的是DEFAULTCAPACITY_EMPTY_ELEMENTDATA,那么如果你插入元素的个数小于等于10,则默认的容量为DEFAULT_CAPACITY,即10。如果你插入的元素的个数(设为x)大于10,则默认的容量为x。
所以,一般来说,默认的初始容量为10。

2.ArrayList扩容多少倍。
通过分析扩容方法:

private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    //可以发现,它先将newCapacity设置为原来的1.5倍
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    //再判断1.5倍的容量是否足够,若不够,则将容量设置为minCapacity
    //minCapacity的值为旧容量值+新增元素个数
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    //1.5倍,也可能太大,比MAX_ARRAY_SIZE还大。
    //若旧容量的1.5倍大于MAX_ARRAY_SIZE,则将容量设置为最大值
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    // minCapacity is usually close to size, so this is a win:
    elementData = Arrays.copyOf(elementData, newCapacity);
}

通过上面的分析可知,一般来说,是1.5倍。
比如说,elementData=10即容量为10,且size=10即元素个数为10,那么新增1个元素,会发生扩容,1.5倍,因此新容量为15。
但假如是批量插入,假如elementData=10,size=10,当新增6个元素,那么旧容量的1.5倍为15,但minCapacity=10+6=16,minCapacity>旧容量的1.5倍,因此,minCapactiy会作为新容量,即新容量为16。
假如扩容后,旧容量的1.5倍大于MAX_ARRAY_SIZE,则会将新容量设置为最大值Integer.MAX_VALUE。

因此,扩容,新容量有可能大于旧容量的1.5倍,有可能小于旧容量的1.5倍。一般来说,就是1.5倍。

3.remove(Object o)和remove(int index)的区别。当Integer i =1;remove(i)调用的是哪一个方法。

remove(Object o)方法移除的是指定的元素o,而remove(int index)方法移除的是指定位置的元素。
假如ArrayList的元素的具体类型是Integer,那么当Integer i =1;根据多态的精确匹配,remove(i)调用的是remove(Object o)方法。即参数i表示的是一个元素,而不是表示一个下标。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值