1. 概述
平常我們開發(fā)中徒仓,可能用的最多的容器就是HashMap。我們來看下HashMap的結構如下圖。
它是由一個Node數組,每個數組元素又是有一個鏈表構成。接下來我們結合源碼來分析下put(),get(),resize()者三個常見的操作。
2. 類成員變量的認識
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // HashMap初始的bucket16.必須是2的n次冪雷滋,原因在后面會涉及到
static final int MAXIMUM_CAPACITY = 1 << 30; //最大容量
static final float DEFAULT_LOAD_FACTOR = 0.75f; //負載因子,估計整個bucket沖突实愚,當到達bucket*0.75容量時维苔,會引起擴容
static final int TREEIFY_THRESHOLD = 8; //當鏈表長度大于這個值時,會轉變成紅黑樹
static final int UNTREEIFY_THRESHOLD = 6; //當樹的節(jié)點低于這個值時會轉變成鏈表
- 關于紅黑樹的介紹榕吼,參見我的下篇文章乱凿,紅黑樹的原理及常見的操作
3. put()函數的解析
put()添加操作的過程如下胁出。
- 對key的hashCode()做hash寺枉,然后再計算index(求余);
- 如果沒碰撞直接放到bucket里;
- 如果碰撞了催式,以鏈表的形式存在buckets后槐脏;
- 如果碰撞導致鏈表過長(大于等于TREEIFY_THRESHOLD),就把鏈表轉換成紅黑樹;
- 如果節(jié)點已經存在就替換old value(保證key的唯一性)
- 如果bucket滿了(超過load factor*current capacity)晶框,就要resize侵贵。
其他的解釋都在源碼中標注。
public V put(K key, V value) {
//對key的hashcode做hash
return putVal(hash(key), key, value, false, true);
}
//onlyIfAbsent為true時,相同的key不會改變替換值。這里的為false补胚,會替換
//evict表示模式瓶逃,為fasle表示處于bucket處于創(chuàng)建階段契沫。這里用true指創(chuàng)建完了会通。
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,則創(chuàng)建bucket
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
//若bucket那個位置為null,則創(chuàng)建新的Node節(jié)點
tab[i] = newNode(hash, key, value, null);
//表示bucket不為null
else {
Node<K,V> e; K k;
//key存在
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//若原來為TreeNode,則插入到紅黑樹種中
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;
//若超過當前容量大小超過capacity*0.75剧浸,則會引起擴容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
注意這里采用的二次hash()操作,不是直接對hashcode再hash。
//hashcode的低16位和高16位做
異或操作
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
- 之所以這樣hash倘待,是采用key的hashcode的低16位和高16位做異或操作啊奄。這樣的好處在于避免hash沖突胧辽。否則人断,它只取低16位暇仲,與高位無關斥滤,那么它有可能會hash沖突嚴重。另外凸克,如果還有更嚴重的沖突蚂维,那么可以采用紅黑樹來解決,事實上Jdk1.8 HashMap也是采用的這樣的思想。
Improve the performance of java.util.HashMap under high hash-collision conditions by using balanced trees rather than linked lists to store map entries. Implement the same improvement in the LinkedHashMap class.
4. get()的解析
get()相對來說就非常簡單了斤吐,過程如下臼婆。
- bucket里的第一個節(jié)點颁独,直接命中寨辩;
- 如果有沖突,則通過key.equals(k)去查找對應的entry
- 若為樹,則在樹中通過key.equals(k)查找缸榛,O(logn)均澳;
- 若為鏈表,則在鏈表中通過key.equals(k)查找辩撑,O(n)开缎。
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判斷bucket是否存在
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//檢查第一個Node(bucket中第一個節(jié)點)是否是要查找的侮邀。
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
//紅黑樹的查找key
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
//遍歷鏈表鹏秋,尋找key相同
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
(n - 1) & hash
就是一個求索引衙传,即求Node數組中的下標。這樣的操作是,當我們的n(表示capacity時)取2的冪的時候购公,例如n取16,那么n-1=15(二進制表示1111)與hash做與操作的時候相當于取余,這樣做比直接取余更高效鹃唯。
5. reSize()的解析
- 當put時,如果發(fā)現(xiàn)目前的bucket占用程度已經超過了Load Factor所希望的比例絮爷,那么就會發(fā)生resize岖寞。在resize的過程仗谆,簡單的說就是把bucket擴充為2倍狸吞,之后重新計算index威始,把節(jié)點再放到新的bucket中。
-
然而又因為我們使用的是2次冪的擴展(指長度擴為原來2倍)星立,所以葬凳,元素的位置要么是在原位置绰垂,要么是在(原位置+舊capacity)的位置。
怎么理解呢火焰?例如我們從16擴展為32時屏富,具體的變化如下所示:
rehash -
這個設計確實非常的巧妙饥追,既省去了重新計算hash值的時間,而且同時,由于新增的1bit是0還是1可以認為是隨機的垛耳,因此resize的過程蓝牲,均勻的把之前的沖突的節(jié)點分散到新的bucket了傅蹂。因此元素在重新計算hash之后励稳,因為n變?yōu)?倍,那么n-1的mask范圍在高位多1bit(紅色)犬金,因此新的index就會發(fā)生這樣的變化:
resize
因此念恍,我們在擴充HashMap的時候碎紊,不需要重新計算hash,只需要看看原來的hash值新增的那個bit是1還是0就好了樊诺,是0的話索引沒變仗考,是1的話索引變成“原索引+oldCap”〈逝溃可以看看下圖為16擴充為32的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) {
//舊的hashMap容量已經達到最大值秃嗜,那么最新的也只能是最大值
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
}
//舊的容量oldThreshold已經存在顿膨,但是沒分配容量锅锨。那么久新的容量=oldThreshold
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);
}
//如果初始化的oldThreshold為0,則重新取整
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) {
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
//尾插法把節(jié)點插入新分配的bucket中恋沃。不帶頭節(jié)點的
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;
}
參考文章: