ArrayList擴容機制探究
阿新 • • 發佈:2022-05-11
一、ArrayList擴容機制探究
1.1 成員變數
//預設初始容量 private static final int DEFAULT_CAPACITY = 10; //空陣列 private static final Object[] EMPTY_ELEMENTDATA = {}; //空陣列,用於預設初始容量的,擴容時會使用 private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; //存放陣列中的元素 transient Object[] elementData; //陣列元素的個數,區別於elementData.length private int size; // private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
1.2 三個建構函式
/*預設的無參構造*/ public ArrayList() { //空陣列,陣列長度為0 this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } /*使用者給定初始容量的建構函式*/ public ArrayList(int initialCapacity) { if (initialCapacity > 0) { //使用者指定的初始容量大於0,則建立一個指定容量的陣列 this.elementData = new Object[initialCapacity]; } else if (initialCapacity == 0) { //使用者指定的初始容量等於0,空陣列,陣列長度為0 this.elementData = EMPTY_ELEMENTDATA; } else { //否則丟擲異常 throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity); } } /*包含特定元素集合的建構函式*/ public ArrayList(Collection<? extends E> c) { Object[] a = c.toArray(); if ((size = a.length) != 0) { if (c.getClass() == ArrayList.class) { elementData = a; } else { elementData = Arrays.copyOf(a, size, Object[].class); } } else { // replace with empty array. elementData = EMPTY_ELEMENTDATA; } }
1.3 Add方法
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } 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++; }
add一個元素的時候,先呼叫了ensureCapacityInternal方法
private void ensureCapacityInternal(int minCapacity) {
//此時elementData還是空陣列,minCapacity=1
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
//Math,max(10,1),返回10
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
//minCapacity=10,elementData.length=0,進入grow方法,當add第二個元素時,elementData.length=10,就不滿足這個條件了,不會進行擴容,直到新增第11個元素。
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
//舊的容量
int oldCapacity = elementData.length;
//新的容量=舊容量的1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
//檢查新容量是否比最小容量還小,還小的話直接將新容量指定為最小容量
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//新容量大於MAX_ARRAY_SIZE,新容量=hugeCapacity(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);
}