首先我们来看一下ArrayList中使用的变量以及构造函数
/** * Default initial capacity. * 默认容量大小 */privatestaticfinalintDEFAULT_CAPACITY=10;/** * Shared empty array instance used for empty instances. * 空对象数组 */privatestaticfinalObject[]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. */privatestaticfinalObject[]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. * 储存数据的数组 */transientObject[]elementData;// non-private to simplify nested class access /** * The size of the ArrayList (the number of elements it contains). * ArrayList中元素的个数 * @serial */privateintsize;
ArrayList一共有三种初始化方法
默认的构造器,将会以默认的大小来初始化内部的数组:public ArrayList();用一个Collection对象来构造,并将该集合的元素添加到ArrayList:public ArrayList(Collectionc)用指定的大小来初始化内部的数组: public ArrayList(int initialCapacity)
源码如下:
/** * 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 */publicArrayList(intinitialCapacity){if(initialCapacity>0){this.elementData=newObject[initialCapacity];}elseif(initialCapacity==0){this.elementData=EMPTY_ELEMENTDATA;}else{thrownewIllegalArgumentException("Illegal Capacity: "+initialCapacity);}}/** * Constructs an empty list with an initial capacity of ten. */publicArrayList(){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 */publicArrayList(Collection