深入理解HashMap的實現原理(java8)
概述
首先,先看一下關於HashMap的源碼,其中有一段的介紹是:
這裏大致的意思就是:
這個哈希表是基於Map接口的實現的,它允許null值和null鍵,它不是線程同步的,同時也不保證有序。
雖然不是很友好,別急,這裏再看一段關於HashMap的源碼的介紹:
解釋:這兩段話,講的是Map的這種實現方式爲get(取)和put(存)帶來了比較好的性能。但是如果涉及到大量的遍歷操作的話,就儘量不要把capacity設置得太高(或load factor設置得太低),否則會嚴重降低遍歷的效率。
影響HashMap性能的兩個重要參數:“initial capacity”(初始化容量)
和“load factor”(負載因子
)。簡單來說,容量就是哈希表桶的個數,負載因子就是鍵值對個數與哈希表長度的一個比值,當比值超過負載因子之後,HashMap就會進行rehash操作來進行擴容。(擴容的相當於之前的兩倍大小)
HashMap的大致結構
HashMap 的大致結構如下圖所示:
其中哈希表是一個數組,我們經常把數組中的每一個節點稱爲一個桶,哈希表中的每個節點都用來存儲一個鍵值對。在插入元素時,如果發生衝突(即多個鍵值對映射到同一個桶上)的話,就會通過鏈表的形式來解決衝突。因爲一個桶上可能存在多個鍵值對,所以在查找的時候,會先通過key的哈希值先定位到桶,再遍歷桶上的所有鍵值對,找出key相等的鍵值對,從而來獲取value。
HashMap的一些重要的屬性
DEFAULT_INITIAL_CAPACITY
: 哈希表初始化的大小
一定要二的冪次,默認初始值是16
MAXIMUM_CAPACITY
:哈希表的最大容量
最大容量2^30
DEFAULT_LOAD_FACTOR
:負載因子
默認值是:0.75
TREEIFY_THRESHOLD
:變成樹型結構的臨界值爲8
-
UNTREEIFY_THRESHOLD
: 恢復鏈式結構的臨界值爲6
-
MIN_TREEIFY_CAPACITY
: 可以對容器進行treeified處理的最小表容量。
transient Node<K,V>[] table
:哈希表
transient int size
: 哈希表中鍵值對的個數
transient int modCount
: 哈希表被修改的次數
-
int threshold
:它是通過capacity*load factor計算出來的,當size到達這個值時,就會進行擴容操作 -
final float loadFactor
: 負載因子
Node類
這裏看一下源碼中關於Node類的介紹:
/**
* Basic hash bin node, used for most entries. (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
*/
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;
}
}
它是 HashMap 中的一個靜態內部類,繼承於Map.Entry<K,V>
接口,哈希表中的每一個節點都是 Node 類型。我們可以看到,Node 類中有 4 個屬性,其中除了 key 和 value 之外,還有 hash 和 next 兩個屬性。hash 是用來存儲 key 的哈希值的,next 是在構建鏈表時用來指向後繼節點的。
HashMap的方法
- get(): get()方法主要調用的是getNode 方法,這裏重點看getNode方法的實現。
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
* Implements Map.get and related methods.
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//如果哈希表不爲空 && key對應的桶上不爲空
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) {
//如果當前的桶是採用紅黑樹處理衝突,則調用紅黑樹的get方法去獲取節點
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//不是紅黑樹的話,那就是傳統的鏈式結構了,通過循環的方法判斷鏈中是否存在該key
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
實現步驟大致如下:
- 通過hash值獲取該key映射到的桶。
- 桶上的key就是要查找的key,則直接命中。
- 桶上的key不是要查找的key,則查看後續節點:
(1)如果後續節點是樹節點,通過調用樹的方法查找該key。
(2)如果後續節點是鏈式節點,則通過循環遍歷鏈查找該key。
- put(): put方法的具體實現也是在putVal方法中,所以我們重點看下面的putVal方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* Implements Map.put and related methods.
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
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;
//如果當前桶沒有碰撞衝突,則直接把鍵值對插入,完事
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//如果桶上節點的key與當前key重複,那這個節點就是我要找了
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//如果是採用紅黑樹的方式處理衝突,則通過紅黑樹的putTreeVal方法去插入這個鍵值對
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//否則就是傳統的鏈式結構
else {
//採用循環遍歷的方式,判斷鏈中是否有重複的key
for (int binCount = 0; ; ++binCount) {
//到了鏈尾還沒找到重複的key,則說明HashMap沒有包含該鍵
if ((e = p.next) == null) {
//創建一個新節點插入到尾部
p.next = newNode(hash, key, value, null);
//如果鏈的長度大於TREEIFY_THRESHOLD這個臨界值,則把鏈變爲紅黑樹
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//找到了重複的key
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//這裏表示在上面的操作中找到了重複的鍵,所以這裏把該鍵的值替換爲新值
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;
}
put方法比較複雜,實現步驟大致如下:
- 先通過hash值計算出key映射到哪個桶。
- 如果桶上沒有碰撞衝突,則直接插入。
- 如果出現碰撞衝突了,則需要處理衝突:
(1)如果該桶使用紅黑樹處理衝突,則調用紅黑樹的方法插入。
(2)否則採用傳統的鏈式方法插入。如果鏈的長度到達臨界值,則把鏈轉變爲紅黑樹。 - 如果桶中存在重複的鍵,則爲該鍵替換新值。
- 如果size大於閾值,則進行擴容。
- remove() :remove方法的具體實現在removeNode方法中,所以我們重點看下面的removeNode方法
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
/**
* Implements Map.remove and related methods.
*
* @param hash hash for key
* @param key the key
* @param value the value to match if matchValue, else ignored
* @param matchValue if true only remove if value is equal
* @param movable if false do not move other nodes while removing
* @return the node, or null if none
*/
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
//如果當前key映射到的桶不爲空
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
//如果桶上的節點就是要找的key,則直接命中
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
//如果是以紅黑樹處理衝突,則構建一個樹節點
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
//如果是以鏈式的方式處理衝突,則通過遍歷鏈表來尋找節點
else {
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
//比對找到的key的value跟要刪除的是否匹配
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
//通過調用紅黑樹的方法來刪除節點
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
//使用鏈表的操作來刪除節點
else if (node == p)
tab[index] = node.next;
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
- hash(): 計算哈希值
/**
* Computes key.hashCode() and spreads (XORs) higher bits of hash
* to lower. Because the table uses power-of-two masking, sets of
* hashes that vary only in bits above the current mask will
* always collide. (Among known examples are sets of Float keys
* holding consecutive whole numbers in small tables.) So we
* apply a transform that spreads the impact of higher bits
* downward. There is a tradeoff between speed, utility, and
* quality of bit-spreading. Because many common sets of hashes
* are already reasonably distributed (so don't benefit from
* spreading), and because we use trees to handle large sets of
* collisions in bins, we just XOR some shifted bits in the
* cheapest possible way to reduce systematic lossage, as well as
* to incorporate impact of the highest bits that would otherwise
* never be used in index calculations because of table bounds.
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
這個hash方法先通過key的hashCode方法獲取一個哈希值,再拿這個哈希值與它的高16位的哈希值做一個異或操作來得到最後的哈希值,爲啥要這樣做呢?註釋中是這樣解釋的:如果當n很小,假設爲64的話,那麼n-1即爲63(0x111111),這樣的值跟hashCode()直接做與操作,實際上只使用了哈希值的後6位。如果當哈希值的高位變化很大,低位變化很小,這樣就很容易造成衝突了,所以這裏把高低位都利用起來,從而解決了這個問題。
- resize(): 初始化表的大小或對錶的擴容操作
HashMap在進行擴容時,使用的rehash方式非常巧妙,因爲每次擴容都是翻倍,與原來計算(n-1)&hash的結果相比,只是多了一個bit位,所以節點要麼就在原來的位置,要麼就被分配到“原位置+舊容量”這個位置。
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
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
}
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);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
//新的resize閾值
threshold = newThr;
//創建新的哈希表@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
//遍歷舊哈希表的每個桶,重新計算桶裏元素的新位置
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
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 { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
//通過上面講的方法來計算節點的新位置
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}