HashMap源碼解析
在 Java8 之前, HashMap 是鏈表散列的數據結構,即數組和鏈表的結合體;從 Java8 開始,引入紅黑樹的數據結構和擴容的優化。
分析版本: JDK1.8
Node
從 Java8 引入紅黑樹之后, HashMap 是由數組、鏈表和紅黑樹組成,發現源碼有些地方與之前不同,那就是 Node :
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
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 ,也就是以前的 Entry ,內容沒變,只是換了一種叫法。
put(K key, V value)
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
transient Node<K,V>[] table;
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
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;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
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;
}
}
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;
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
final Node<K,V>[] resize() {
....
}
Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {
return new Node<>(hash, key, value, next);
}
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
....
}
final void treeifyBin(Node<K,V>[] tab, int hash) {
....
}
void afterNodeAccess(Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { }
}
HashMap 使用哈希表來存儲。哈希表為解決沖突,可以采用開放地址法和鏈地址法等來解決問題,Java 中 HashMap 采用了鏈地址法。鏈地址法,就是數組加鏈表的結合。在每個數組元素上都一個鏈表結構,當數據被Hash后,得到數組下標,把數據放在對應下標元素的鏈表上。
當我們往 HashMap 中 put 元素的時候,先根據 key 的 hashCode 重新計算 hash 值,根據 hash 值再通過高位運算和取模運算得到這個元素在數組中的位置(即下標),如果數組該位置上已經存放有其他元素了,那么在這個位置上的元素將以鏈表的形式存放,新加入的放在鏈頭,最先加入的放在鏈尾,如果該鏈表超出 8 個的話,就轉換成紅黑樹。如果數組該位置上沒有元素,就直接將該元素放到此數組中的該位置上。
hash(Object key)
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
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 {
....
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);//取hashCode值和高位參與運算
}
}
定位位置的方法通過以上三個步驟得到,取 key 的 hashCode 的值,然后進行無符號右移 16 位,再與現有哈希桶數組的大小取模。通過 (n - 1) & hash 來得到該對象的保存位求得這個位置的時候,馬上就可以知道對應位置的元素,不用遍歷鏈表,大大優化了查詢的效率。
當 length 總是 2 的 n 次方時,(length - 1) & hash 運算等價于對 length 取模,也就是h % length,但是 & 比 % 具有更高的效率。
注意,在 Java8 之前的算法是這樣的:
static int hash(int h) {
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
static int indexFor(int hash, int length) {
return hash & (length-1);
}
Java8 優化了高位運算的算法,通過 hashCode() 的高 16 位異或低 16 位實現的:(h = k.hashCode()) ^ (h >>> 16),主要是從速度、功效、質量來考慮的,這么做可以在數組 table 的 length 比較小的時候,也能保證考慮到高低 Bit 都參與到 Hash 的計算中,同時不會有太大的開銷。

putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict)
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
transient Node<K,V>[] table;
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)//如果為null或者大小為0則創建
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)//計算index
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))//如果有key,那么直接覆蓋value
e = p;
else if (p instanceof TreeNode)//是否是紅黑樹
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {//為鏈表
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);//鏈表長度大于8轉換為紅黑樹進行處理
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;
}
}
- 當 table 數組為 null 或者大小為 0 的時候進行擴容。
- 第二步,計算出該 key 的索引 index 。
- 找到 table 數組中該位置,判斷該位置上是否有值:
- 如果有,判斷 key 的 hashCode() 和 equals() 是否相等,相等的話覆蓋,不相等的話再判斷是否是紅黑樹還是鏈表。
- 如果沒有,判斷是不是紅黑樹:
- 是,就插入到紅黑樹中;
- 不是話,遍歷鏈表,如果大小大于8,轉換成紅黑樹,插入到紅黑樹中,不大于8的話就插入到鏈表,如果在遍歷的是否發現hashCode() 和 equals() 相等。
- 插入成功后,判斷 table 數組大小是否超過了最大容量,是的話擴容
resize()
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
static final int MAXIMUM_CAPACITY = 1 << 30;
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
static final float DEFAULT_LOAD_FACTOR = 0.75f;
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) {//擴容前的舊的數組大小如果已經達到最大(2^30)
threshold = Integer.MAX_VALUE;////修改最大容量為int的最大值(2^31-1),這樣以后就不會擴容了
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)//擴容后的小于數組大小最大值
newThr = oldThr << 1; // double threshold 在舊值上乘以2
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;//舊的最大容量就是新的數組容量
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;//16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//0.75*16
}
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;//新的table數組
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;//給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 {//原來的索引+oldCap
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {//原索引放到新table數組里
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {//原索引+oldCap放到新table數組里
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
}
來自:http://yydcdut.com/2016/12/06/hashmap-analyse/