java基础集合类——ArrayList 源码略读

ArrayList是java的动态数组,底层是基于数组实现。

1. 成员变量

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    /**
     * The maximum size of array to allocate.
     * Some VMs reserve some header words in an array.
     * Attempts to allocate larger arrays may result in
     * OutOfMemoryError: Requested array size exceeds VM limit
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * Default initial capacity.
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * Shared empty array instance used for empty instances.
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * Shared empty array instance used for default sized empty instances. We
     * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
     * first element is added.
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;

一个个来看一下这些成员变量。

  • elementData
    这是ArrayList的基本数据类型,因为java并没有真的实现底层泛型,而是通过实现编译类型擦除的方式实现了泛型的效果。因此,底层的数组是Object[]类型。

  • size
    这个并不是指elementData数组的长度,而是有效存储信息的长度,初始化时为0

  • DEFAULT_CAPACITY
    这是一个常量,这是初始化时elementData的长度。

  • DEFAULTCAPACITY_EMPTY_ELEMENTDATA & EMPTY_ELEMENTDATA
    这两个都是常量,而且都是空数组。

  • MAX_ARRAY_SIZE
    最大数组长度,超过此长度会报错

2. 成员函数

学习成员函数的代码,主要是看外部变动发生时,底层数组会怎么变化。其实吧,ArrayList并不复杂,无法怎么变化,都是elementData的增删改查,剩下的无非是对效率的优化。

2.1 初始化

    /**
     * Constructs an empty list with the specified initial capacity.
     *
     * @param  initialCapacity  the initial capacity of the list
     * @throws IllegalArgumentException if the specified initial capacity
     *         is negative
     */
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

这里有三个有趣的初始化方法。

  • 带初始化capacity参数
    这个不用说,直接用capicity来初始化elementData数组,再加上对传入参数的防御性检查,其他的没了。

  • 不带初始化参数
    这个直接用DEFAULTCAPACITY_EMPTY_ELEMENTDATA赋值给elementData

  • 传入一个集合实例
    这个方法也很有趣,如果传入的集合不为空,则不用说,直接将对方的数组复制过来就行。但是如果对方为空列表,elementData赋值为EMPTY_ELEMENT_DATA。为什么不用DEFAULT_ELEMENT_DATA,主要不同点在于添加元素时的应对策略不同。

2.2 追加元素时

    /**
     * Appends the specified element to the end of this 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) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    /**
     * Increases the capacity to ensure that it can hold at least the
     * number of elements specified by the minimum capacity argument.
     *
     * @param minCapacity the desired minimum capacity
     */
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        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);
    }

    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

这方法调用链还挺长的,先从头来。

  1. add(Object e)
    很简单的思路,直接将当前有效元素最大索引后面的位置放置这个新增元素就行,然后将size++。唯一需要考虑的是,如果当前数组已经放满的时候,或者为空的时候(例如前面不带初始化capacity会将elementData赋值为空数组),这个时候需要对数组进行扩充了。

  2. ensureCapacityInternal
    这里可以看出来DEFAULT_EMPTY_ELEMENTDATA与EMPTY_ELEMENTDATA的区别了,如果是DEFAULT_EMPTY_ELEMENTDATA,直接扩充为10,如果为EMPTY_ELEMENTDATA,实际上也被视为是有值的,会根据0的size来进行扩充。扩充的策略看方法3。

  3. ensureExplicitCapacity
    简单的校验,如果当前length已经不足以支持新的元素,需要扩充。扩充策略见方法4。

  4. grow
    不看那些防御性代码,ArrayList的防御性措施只有一个,扩充为原先size的150%。因此如果elementData为EMPTY_ELEMENTDATA,则扩充为1,如果为DEFAULT_EMPTY_ELEMENTDATA,则扩充为10。
    为什么这样考虑,我想主要类型一致,因为初始化时传入一个原始列表长度为6,则首轮扩充要扩充到9个,既然同类都扩充为原先的150%,那么传入一个空列表凭什么可以扩充不符合规划的10,除非将空列表排除出列表的范围。这样做也是挺合理,就是这个实现方式有点恶心,而且这个变量命名非常不好,容易混淆。
    而且也需要注意到这个扩充幅度不大,可以节省空间,但是如果需要加入特别大的size队列时,那就需要扩充相当多次,这时还是比较推荐初始化就设置好对应的capacity比较好。

2.3 中间添加元素

这是一个比较恶心的方法,你需要将原先在这个位置的元素往后移,而且还要将这个原先元素后面的所有元素都往后移,才能空出空间给新增元素。耗时耗力,总之,很恶心的代码。

    /**
     * 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) {
        rangeCheckForAdd(index); // 防御性措施,无实质作用

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

2.4 移除代码

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

删除时,将直接将后面的元素移到前面覆盖,注意将最后一个元素转为null,这是为了让已经不使用的元素能够被gc掉。

2.5 清空

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

这个clear需要额外注意,从源码看得出来,clear时只会将elementData的引用置为null,但是elementData数组的长度并没有缩减。如果在大数据量下,需要复用ArrayList,reset的时候仅是调用了clear方法,会导致不小的内存被elementData数组所占用。

2.6 其他方法

像iterator,foreach之类的方法大概也没什么好讲的,ArrayList篇先这样。

猜你喜欢

转载自www.cnblogs.com/oreo/p/10793682.html