下來看JDK8中的屬性DEFAULT_INITIAL_CAPACITY,以下所示:java
List-1 spa
/** * The default initial capacity - MUST be a power of two. */ static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
當進行put時,使用哪一個bucket,計算方式以下:code
List-2 ci
int index=(table.length-1)&hash
因爲table.length的值老是2的冪次方,因此table.length-1的值,轉換爲二進制後最右邊的幾位都是1。好比table.length的值是16,那麼table.length-1的二進制是1111。因此作&運算時,值是多少很大程度上取決於hash的值,這樣作是爲了減小hash碰撞,爭取將entry均勻的分散在bucket中。源碼
看JDK8中HashMap的源碼片斷,以下:hash
List-3 it
final Node<K,V>[] resize() { Node<K,V>[] oldTab = table; int oldCap = (oldTab == null) ? 0 : oldTab.length; int oldThr = threshold; int newCap, newThr = 0; if (oldCap > 0) { if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // double threshold }
注意newCap = oldCap << 1這條語句,oldCap=oldTable.length,因此擴容時capacity是翻倍。table