ArrayList有三種初始化方式: 1.指定大小初始化 public ArrayList(int initialCapacity) 2.傳入一個Collection對象初始化,並將對象中的數據添加到ArrayList中 public ArrayList(Collection<? extends E ...
ArrayList有三種初始化方式:
1.指定大小初始化 public ArrayList(int initialCapacity)
2.傳入一個Collection對象初始化,並將對象中的數據添加到ArrayList中 public ArrayList(Collection<? extends E> c)
3.預設構造函數初始化 public ArrayList()
預設長度:
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
從上面可以看出當使用無參構造函數創建ArrayList時,預設長度為0
調用add方法添加元素時
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}//預設空數組
private int size;//元素個數
transient Object[] elementData;//存放元素的數組
private static final int DEFAULT_CAPACITY = 10;//預設容量
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;//int最大值-8
//添加元素
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
//確保內部容量,將元素個數與數組長度比較判斷是否擴容
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)//如果最小需要容量大於數組長度,將數組擴容
grow(minCapacity);
}
//計算最小需要容量
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
//擴容
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);//將數組長度的二進位表達形式右移,相當於原來的0.5倍,每次擴容1.5倍
if (newCapacity - minCapacity < 0)//如果新容量小於最小需要容量,則將新容量設置為最小容量
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)//如果新容量大於int最大值減8,則將新容量設置為int類型的最大容量
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
//巨大容量
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
從上述代碼可以看出,當第一次調用add添加元素時ArrayList才會設置數組預設長度10,之後每超出數組長度就會進行擴容,每次擴容是原來的1.5倍