紅黑樹在HashMap中的應用
我們知道在jdk1.8之前,HashMap採用鏈表的方式解決衝突,不過在更新1.8版本之後,
HashMap採用了鏈表加紅黑樹的方式來優化了結構。
話不多說,我們來看源碼:
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*/
static final int TREEIFY_THRESHOLD = 8;
結點數量達到8個將鏈表轉爲紅黑樹/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
*/
static final int UNTREEIFY_THRESHOLD = 6;
resize時,如果結點數量小於6個,還是用鏈表最常用的put()方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true); //put()方法轉putVal()
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) { //evict爲false,the table is in creation mod
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0) //初次put時會擴容
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null) //如果tab[index]處沒有元素,則直接將這對(key,value)放到這
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以前時第一個位置,則更新
e = p;
else if (p instanceof TreeNode) //如果不是的話,判斷p是不是紅黑樹結構
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); //時紅黑樹就調用紅黑樹put方法
else { //是鏈表結構
for (int binCount = 0; ; ++binCount) { //遍歷鏈表
if ((e = p.next) == null) { 判斷鏈表數量是否大於等於TREEIFY_THRESHOLD-1,決定是否要將鏈表轉換成紅黑樹
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) //onlyIfAbsent爲true,則不需要更新value值
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
這裏出現了兩個以前沒有的參數,onlyIfAbsent和evict。
onlyIfAbsent:onlyIfAbsent if true, don't change existing value。
在oldValue不爲null時,如果onlyIfAbsent爲true則不更新value值。
當然這個值默認爲false,是會正常更新的。
evict:evict if false, the table is in creation mode.標記狀態,默認爲true
當鏈表長度大於等於8時,則會將鏈表轉換爲紅黑樹存儲
static final int TREEIFY_THRESHOLD = 8