我正在瀏覽ArrayList的源代碼。我遇到了方法ensureCapacity(),它增加了內部使用的數據數組的容量。其中,根據邏輯int newCapacity = (oldCapacity * 3)/2 + 1;
增加數據陣列的新容量,其中舊容量是當前數據陣列的大小。是否有任何特別的理由選擇(oldCapacity * 3)/2 + 1
作爲新的數組大小,如果是這樣的話?ArrayList中ensureCapacity方法中使用的邏輯
/**
* Increases the capacity of this <tt>ArrayList</tt> instance, if
* necessary, to ensure that it can hold at least the number of elements
* specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
public void ensureCapacity(int minCapacity) {
modCount++;
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
Object oldData[] = elementData;
int newCapacity = (oldCapacity * 3)/2 + 1;
if (newCapacity < minCapacity)
newCapacity = minCapacity;
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
在此先感謝...
我只是看着Java 6的ArrayList實現,我找不到你提到的那一行。這是來自Effective Java嗎? – helpermethod 2010-07-26 15:35:02
@Helper方法:你的java impl的供應商是什麼?在sun jdk中,我看到了提到的這一行。 – Roman 2010-07-26 15:38:54
我正在使用Sun JDK 1.6.0-b105。 – vcosk 2010-07-26 16:07:54