HashMap之Put方法解讀
阿新 • • 發佈:2019-02-10
HashMap底層是使用Entry物件陣列儲存的,而Entry是一個單項的連結串列或者是紅黑樹。
下面是對HashMap的put原始碼的解讀
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;
/*根據 hash 值確定節點在陣列中的插入位置,若此位置沒有元素則進行插入,
注意確定插入位置所用的計算方法為 (n - 1) & hashCode(key),由於n
一定是2的冪次,這個操作相當於hash % n */
//如果index位置對應的沒有key
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null); //就建立一個新節點
else {//待插入的位置存在元素
Node<K,V> e; K k;
//比較原來元素的hash值和key值
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//如果key和hash值相等,不操作
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);
//如果連結串列個數超過6就將連結串列結構轉為紅黑樹結構
if (binCount >= TREEIFY_THRESHOLD - 1)
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;
}
在HashMap中使用物件作為key的情況,都說用可變物件是很危險的,順便就把HashMap中的Put看了一遍