/** * 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(int initialCapacity){ super(); //如果传入的数组初始长度小于0,抛出异常 if (initialCapacity < 0) thrownew IllegalArgumentException("Illegal Capacity: "+ initialCapacity); //创建一个 Object数组 来存放元素 this.elementData = new Object[initialCapacity]; } /** * Constructs an empty list with an initial capacity of ten. */ publicArrayList(){ //如果没有指定长度,默认是10 this(10); }
/** * Increases the capacity of this <tt>ArrayList</tt> instance, if * necessary, to ensure that it can hold at least the number of elements * specified by the minimum capacity argument. * * @param minCapacity the desired minimum capacity */ //指定ArrayList长度的方法,实际上就是设置Object数组的长度 publicvoidensureCapacity(int minCapacity){ //校验设置的长度是否大于0 if (minCapacity > 0) ensureCapacityInternal(minCapacity); }
privatevoidensureCapacityInternal(int minCapacity){ //用于标示当前ArrayList长度是否改变,用于线程安全 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 */ privatevoidgrow(int minCapacity){ // overflow-conscious code //存储以前的长度 int oldCapacity = elementData.length; //"oldCapaticy>>1"表示baseValue右移1位,即除以2 int newCapacity = oldCapacity + (oldCapacity >> 1); //如果 newCapacity 比设定长度小,把设定长度放入 newCapacity if (newCapacity - minCapacity < 0) newCapacity = minCapacity; //如果 newCapacity 比数组的最大值大 if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: //如果 newCapacity>minCapacity 且 newCapacity<MAX_ARRAY_SIZE, //原来的数组数据拷贝到新数组,并设置新数组长度是 newCapacity elementData = Arrays.copyOf(elementData, newCapacity); } /** * 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 */ //最大数组长度设置成 Integer 最大值减 8 privatestaticfinalint MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;