ArrayList源碼分析
1、增加元素
ArrayList有兩個不同的add()
方法。常用的就是第一個,添加元素到list的末尾,只分析第一個方法。
/**
* 將指定的元素添加到列表末尾.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
//確認List容量
ensureCapacityInternal(size + 1); // Increments modCount!!
//把元素放到List的末尾
elementData[size++] = e;
return true;
}
來看ensureCapacityInternal(size + 1); // Increments modCount!!
執行的是以下方法,size是當前ArrayList
的大小0:
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); //calculateCapacity執行的是下面的靜態方法calculateCapacity
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
在 calculateCapacity
方法中對elementData
進行檢查,如果它是DEFAULTCAPACITY_EMPTY_ELEMENTDATA
的,就返回size和DEFAULT_CAPACITY
兩者中的最大值,第一次添加元素時,擴容到默認值10。
調用無參構造的時候,把DEFAULTCAPACITY_EMPTY_ELEMENTDATA
賦值給了 elementData
,此時一定是它。
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
DEFAULT_CAPACITY
默認爲10.
/**
* Default initial capacity.
*/
private static final int DEFAULT_CAPACITY = 10;
源碼中對elementData
的註釋寫的很清楚,如果 一個ArrayList
的elementData
是 DEFAULTCAPACITY_EMPTY_ELEMENTDATA
,那麼在第一次添加元素時就擴容爲默認容量10.
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access
下面這一步就是很重要的擴容了,calculateCapacity
返回ArrayList
的大小之後,執行ensureExplicitCapacity
,modCount++
,然後判斷元素的length
和minCapacity
的大小,在第一次增加元素的時候,會進入grow
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
擴充:
/**
* 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) {
// 獲取當前數組容量
int oldCapacity = elementData.length;
//擴容,新數組容量 = 當前數組容量 + 當前數組容量/2
//右移除以2的幾次冪,左移乘以2的幾次冪
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);
}
大容量分配:
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
//判斷想要的是否大於臨界值,如果大於,則返回Integer.MAX_VALUE(0x7fffffff),否則返回MAX_ARRAY_SIZE
return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
}
MAX_ARRAY_SIZE爲什麼要-8
?
因爲某些VM
會在數組中保留一些頭字,嘗試分配這個最大存儲容量,可能會導致Array
容量大於VM
的limit
,最終導致OutOfMemoryError
/**
* The maximum size of array to allocate.
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
然後增加的過程就完事了。
未完待續。。。
很快!