java8源碼
ArrayList 總的來說就是一個動態數組,擴容時會變1.5倍容量
默認構造
一個空數組的arraylist
分析幾個重要的方法
add(E)方法
每次調用此方法,會先檢查是否需要擴容,,
ensureCapacityInternal(size + 1) ,,,默認 1.5倍擴容 int newCapacity = oldCapacity + (oldCapacity >> 1);
此時會修改modCount,,modCount用來檢查併發修改異常,,,發現modCount出現變化就會拋出 throw new ConcurrentModificationException();
remove(int index) 方法
首先會檢測索引範圍 rangeCheck(index) 超過了就拋出 IndexOutOfBoundsException
修改 modCount
索引舊的值 以便返回
數組刪除索引之後的全部往前挪,System.arraycopy(elementData,index + 1, elementData, index, numRemoved)
數組最後一位置空,elementData[--size] = null; 讓gc回收掉這個對象
get(int index) 方法
首先會檢索範圍 rangeCheck(index)
返回索引對象 elementData[index]
set(int index,E element) 方法
範圍檢查
替換值 elementData[index] = element;
clear() 方法
修改modCount
數組所有位置 挨個設置成null,,,let gc work
size 設置成0
addAll(Collection<? extend E> c) 方法
將c容器變成數組 Object[] a = c.toArray(); toArray方法一般會將容器內容重新拷貝到一個新的數組裏面去
檢查是否需要擴容 oldSize + a.length
將a數組複製到ArrayList的數組
重新設置size += a.length;
iterator() 方法
,,return new Itr(); Itr是ArrayList的一個內部類。數據還是引用外部類ArrayList的數據,,並沒有重新Copy一個
Itr 實現了Iterator 接口
hasNext() {
return cursor != size;
}
E next() {
檢查併發修改
獲取ArrayList.this.elementData;
返回獲取的elementData[當前遊標位置]
}