把之前的學習筆記整理了一下。寫在博客上面,好方便以後的查看,順便也複習一下,裏面有什麼不對的地方,歡迎大家提出,萌萌噠~。
1.ArrayList是基於數組實現的,是一個動態數組,其容量能自動增長,類似於C語言中的動態申請內存,動態增長內存。
2. ArrayList不是線程安全的,只能用在單線程環境下,多線程環境下可以考慮用Collections.synchronizedList(List list)函數返回一個線程安全的ArrayList類,也可以使用concurrent併發包下的CopyOnWriteArrayList類。
/**
* 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;
//MAX_ARRAY_SIZE=Integer.MAX_VALUE - 8 ArrayList最大可分配的容量
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);
}