Java源码分析-ArrayList

ArrayList介绍

ArrayList实现了AbstractList抽象类,同时还继承了List,AccessRandom,Cloneable,java.io.Serializable接口,根据源码可知ArrayList也是实现泛型的机制。

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

AbstractList是List的抽象类,ArrayList实现AbstractList抽象类的同时还继承了List接口,而实现了RandomAccess接口的原因是ArrayList需要进行随机访问,底层是线性数组的实现方式,所以如果采用实现RandomAccess接口的方式算法会更高效。实现了Cloneable接口,能被克隆,实现了java.io.Serializable能够被序列化 。

ArrayList属性

private static final long serialVersionUID = 8683452581122892189L;

    /**
     * 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
  • serialVersionUID是ArrayList实现了Serializable必须要生成的一个序列化的值。
  • DEFAULT_CAPACITY 这个是指ArrayList初始化的默认大小,对于有初始化容量大小的构造函数,如果初始容量的参数是大于零的,则会初始化出来容量为10的ArrayList,如果初始化的时候容量参数是零,就初始化出空的ArrayList,其他情况就抛出异常。

    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);
        }
    }
  • EMPTY_ELEMENTDATA 和DEFAULTCAPACITY_EMPTY_ELEMENTDATA 都是表示的是空的数据类型,但是这两个的的区别在于,当添加完第一个元素的时候,后者知道要扩充多少。

你可能感兴趣的:(Java,SE,java,源码)