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看了一遍