ArrayList比較簡單,主要是通過數組來實現的
需要注意的是其初始容量是10
/** * Default initial capacity. */ private static final int DEFAULT_CAPACITY = 10;
需要注意增長方法grow()
/** * 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 */ private void grow(int minCapacity) { // overflow-conscious code int 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); }
只要size > 數組的長度,就會觸發grow,其中增長比例是原來的容量的一半
int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1);
然后把原來數組的內容拷貝到新的數組
========================================================================分割線========================================================
ArrayList和LinkedList的區別
ArrayList是通過數組來實現的,讀取性能很高,隨機訪問時間復雜度為O(1),適用於讀大於寫的場景
LinkedList是是通過雙向隊列來實現的,更新效率更高,寫只需要修改前后兩個節點的相關引用,但是讀取效率比較低,需要最多遍歷一半長度的隊列,適用與寫大於讀的場景