ArrayList,HashMap,LinkedList 初始化大小和 擴容機制
阿新 • • 發佈:2019-02-11
前面寫這篇文章的時候,看的是JDK1.6,然後就被下面的評論的人噴成了垃圾,是我沒有說明清楚。
1.ArrayList
jdk1.6 的原始碼
/** * Constructs an empty list with the specified initial capacity. */ public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity]; } /** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { //初始化大小10 this(10); }
/** * 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; //原始大小的1.5 + 1 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); } }
ArrayList 初始化大小是 10 (如果你知道你的arrayList 會達到多少容量,可以在初始化的時候就指定,能節省擴容的效能開支)
擴容點規則是,新增的時候發現容量不夠用了,就去擴容
擴容大小規則是,擴容後的大小= 原始大小+原始大小/2 + 1。(例如:原始大小是 10 ,擴容後的大小就是 10 + 5+1 = 16)
jdk1.7
/** * Shared empty array instance used for empty instances. */ private static final Object[] EMPTY_ELEMENTDATA = {}; ···省略 /** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { super(); //初始化大小0 this.elementData = EMPTY_ELEMENTDATA; }
/**
* 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;
//直接是1.5 倍
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);
}
擴容大小規則是,擴容後的大小= 原始大小+原始大小/2 。(例如:原始大小是 10 ,擴容後的大小就是 10 + 5 = 15, 15+15/2 = 22, 22+22/2 = 33)
2.linkedList
linkedList 是一個雙向連結串列,沒有初始化大小,也沒有擴容的機制,就是一直在前面或者後面新增就好。
對於雙向連結串列的理解
3.HashMap
HashMap 初始化大小是 16 ,擴容因子預設0.75(可以指定初始化大小,和擴容因子)
擴容機制.(當前大小 和 當前容量 的比例超過了 擴容因子,就會擴容,擴容後大小為 一倍。例如:初始大小為 16 ,擴容因子 0.75 ,當容量為12的時候,比例已經是0.75 。觸發擴容,擴容後的大小為 32.)