HashMap中數據結構
在jdk1.7中,HashMap采用數組+鏈表(拉鏈法)。因為數組是一組連續的內存空間,易查詢,不易增刪,而鏈表是不連續的內存空間,通過節點相互連接,易刪除,不易查詢。HashMap結合這兩者的優秀之處來提高效率。
而在jdk1.8時,為了解決當hash碰撞過於頻繁,而鏈表的查詢效率(時間復雜度為O(n))過低時,當鏈表的長度達到一定值(默認是8)時,將鏈表轉換成紅黑樹(時間復雜度為O(lg n)),極大的提高了查詢效率。
如圖所示:
HashMap初始化
以下代碼未經特別聲明,都是jdk1.8。
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
HashMap的默認大小是16。查看HashMap
的構造方法,發現沒有執行new操作,猜測可能跟ArrayList
一樣是在第一次add
的時候開辟的內存,於是查看put
方法。
put方法
關於Node節點
HashMap將hash,key,value,next已經封裝到一個靜態內部類Node上。它實現了Map.Entry<K,V>
接口。
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
然后在定義一個Node數組table
transient Node<K,V>[] table;
hash實現
當我們put的時候,首先計算 key
的hash
值,這里調用了 hash
方法,hash
方法實際是讓key.hashCode()
與key.hashCode()>>>16
進行異或操作,高16bit補0,一個數和0異或不變,所以 hash 函數大概的作用就是:高16bit不變,低16bit和高16bit做了一個異或,目的是減少碰撞。按照函數注釋,因為bucket數組大小是2的冪,計算下標index = (table.length - 1) & hash
,如果不做 hash 處理,相當於散列生效的只有幾個低 bit 位,為了減少散列的碰撞,設計者綜合考慮了速度、作用、質量之后,使用高16bit和低16bit異或來簡單處理減少碰撞,而且JDK8中用了復雜度 O(logn)的樹結構來提升碰撞下的性能。
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
實現方法
- 如果當前數組table為null,進行resize()初始化
- 否則計算數組索引
i = (n - 1) & hash
- 如果這個table[i]值為空,那么就將這個Node鍵值對放在這里
- 判斷key是否與table[i]重復,重復則替換
- 不重復在判斷table[i]是否連接了一個鏈表,鏈表為空則new 一個Node鍵值對,鏈表不為空就循環直到最后一個節點的next為null或者出現出現重復key值
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 默認容量初始化
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//如果table[i]為空,那就把這個鍵值對放在table[i], i = (n - 1) & hash 相等於 hash % n,
//但是hash后按位與 n-1,比%模運算取余要快
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//當另一個key的hash值已經存在時
else {
Node<K,V> e; K k;
// table[i].key == key
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//JDK8在哈希碰撞的鏈表長度達到TREEIFY_THRESHOLD(默認8)后,
//會把該鏈表轉變成樹結構,提高了性能。
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//遍歷table[i]所對應的鏈表,直到最后一個節點的next為null或者有重復的key值
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//key重復,替換value
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
// Callbacks to allow LinkedHashMap post-actions
void afterNodeAccess(Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { }
void afterNodeRemoval(Node<K,V> p) { }
get方法
首先通過hash
函數找到索引,然后判斷map為null,再判斷table[i]是否等於key,然后在找與table相連的鏈表的key是否相等。
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
jdk1.7中的線程安全問題(resize死循環)
當HashMap的size超過Capacity*loadFactor時,需要對HashMap進行擴容。具體方法是,創建一個新的,長度為原來Capacity兩倍的數組,保證新的Capacity仍為2的N次方,從而保證上述尋址方式仍適用。同時需要通過如下transfer方法將原來的所有數據全部重新插入(rehash)到新的數組中。
下列代碼基於 jdk1.7.0_79
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
for (Entry<K,V> e : table) {
while(null != e) {
Entry<K,V> next = e.next;
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
}
}
}
該方法並不保證線程安全,而且在多線程並發調用時,可能出現死循環。其執行過程如下。從步驟2可見,轉移時鏈表順序反轉。
- 遍歷原數組中的元素
- 對鏈表上的每一個節點遍歷:用next取得要轉移那個元素的下一個,將e轉移到新數組的頭部,使用頭插法插入節點
- 循環2,直到鏈表節點全部轉移
- 循環1,直到所有元素全部轉移
單線程rehash
單線程情況下,rehash無問題。下圖演示了單線程條件下的rehash過程
多線程並發下的rehash
這里假設有兩個線程同時執行了put操作並引發了rehash,執行了transfer方法,並假設線程一進入transfer方法並執行完next = e.next后,因為線程調度所分配時間片用完而“暫停”,此時線程二完成了transfer方法的執行。此時狀態如下。
接着線程1被喚醒,繼續執行第一輪循環的剩余部分
e.next = newTable[1] = null
newTable[1] = e = key(5)
e = next = key(9)
結果如下圖所示
接着執行下一輪循環,結果狀態圖如下所示
此時循環鏈表形成,並且key(11)無法加入到線程1的新數組。在下一次訪問該鏈表時會出現死循環。
jdk1.8中的擴容
在jdk1.8中采用resize方法來對HashMap進行擴容。
resize方法
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;
}
// 沒超過最大值,就擴充為原來的2倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 計算新的resize上限
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
// 把每個bucket都移動到新的buckets中
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
// 清除原來table[i]中的值
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // 帶有鏈表時優化重hash
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
// 原索引,(e.hash & oldCap) == 0 說明 在put操作通過 hash & newThr
//計算出的索引值等於現在的索引值。
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
// 原索引+oldCap,不是原索引,就移動原來的長度
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
// 原索引放到bucket里
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
// 原索引+oldCap放到bucket里
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
聲明兩對指針,維護兩個鏈表,依次在末端添加新的元素,在多線程操作的情況下,無非是第二個線程重復第一個線程一模一樣的操作。
因此不會產生jdk1.7擴容時的resize死循環問題。
jdk1.8中hashmap的確不會因為多線程put導致死循環,但是依然有其他的弊端。因此多線程情況下還是建議使用concurrenthashmap。
面試問題
-
如果new HashMap(19),bucket數組多大?
HashMap的bucket 數組大小一定是2的冪,如果new的時候指定了容量且不是2的冪,實際容量會是最接近(大於)指定容量的2的冪,比如 new HashMap<>(19),比19大且最接近的2的冪是32,實際容量就是32。
基礎知識
簡便方法:
如對a
按位取反,則得到的結果為-(a+1)
。
此條運算方式對正數負數和零都適用。
源碼/** * Returns a power of two size for the given target capacity. */ static final int tableSizeFor(int cap) { int n = cap - 1; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; }
解析
先來分析有關n位操作部分:先來假設n的二進制為01xxx...xxx。接着
對n右移1位:001xx...xxx,再位或:011xx...xxx
對n右移2為:00011...xxx,再位或:01111...xxx
此時前面已經有四個1了,再右移4位且位或可得8個1
同理,有8個1,右移8位肯定會讓后八位也為1。
綜上可得,該算法讓最高位的1后面的位全變為1。
最后再讓結果n+1,即得到了2的整數次冪的值了。
現在回來看看第一條語句:
int n = cap - 1;
讓cap-1再賦值給n的目的是另找到的目標值大於或等於原值。例如二進制1000,十進制數值為8。如果不對它減1而直接操作,將得到答案10000,即16。顯然不是結果。減1后二進制為111,再進行操作則會得到原來的數值1000,即8。
這種方法的效率非常高,可見Java8對容器優化了很多,很強哈。其他之后再進行分析吧。 -
HashMap什么時候開辟bucket數組占用內存?
HashMap在new 后並不會立即分配bucket數組,而是第一次put時初始化,類似ArrayList在第一次add時分配空間。 -
HashMap何時擴容?
HashMap 在 put 的元素數量大於 Capacity * LoadFactor(默認16 * 0.75) 之后會進行擴容。 -
當兩個對象的hashcode相同會發生什么?
碰撞 -
如果兩個鍵的hashcode相同,你如何獲取值對象?
遍歷與hashCode值相等時相連的鏈表,直到相等或者null -
你了解重新調整HashMap大小存在什么問題嗎?
參考文檔