/** * Constructs an empty list with the specified initial capacity. * * @param initialCapacity the initial capacity of the list * @throwsIllegalArgumentException if the specified initial capacity * is negative */publicArrayList(int initialCapacity) {if (initialCapacity >0) {this.elementData=newObject[initialCapacity]; } elseif (initialCapacity ==0) {this.elementData= EMPTY_ELEMENTDATA; } else {thrownewIllegalArgumentException("Illegal Capacity: "+ initialCapacity); } }
/** * 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}) * 添加指定的元素到List的末尾 */publicbooleanadd(E e) {ensureCapacityInternal(size +1); // 扩充数组长度 elementData[size++] = e; // 最后一个赋值为ereturntrue; }
那么它是如何扩充数组长度的呢?追踪代码来到**grow(int minCapacity)**方法:
/** 可以看到它是通过Arrays.copyOf方法将原数组拷贝到了一个数组长度为newCapacity的新数组里面*/privatevoidgrow(int minCapacity) {// overflow-conscious codeint 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); }