HashMap存儲數據時,調用put方法,源碼及分析如下所示:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* Implements Map.put and related methods.
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
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)
// 1、首次插入數據時,初始化數組
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
// 2、當對應桶中無數據時,將元素存入數組中
tab[i] = newNode(hash, key, value, null);
else {
// 3、對應桶中有數據
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
// 3.1 數組中元素的key與傳入的key相同時,返回對應的節點
e = p;
else if (p instanceof TreeNode)
// 3.2 當數據中的節點爲樹節點時,將數據存入紅黑樹中,並返回對應節點
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
// 3.3 數組中元素的key與傳入的key不同,且不爲樹節點時,遍歷該桶對應的鏈表
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
// 鏈表遍歷完了仍未找到key相同的節點時,將數據添加到鏈表尾
p.next = newNode(hash, key, value, null);
// 如果鏈表長度大於等於樹化閾值(8)時,進行樹化操作
// (1)當數組長度小於最小樹化容量閾值(64)時,進行數組擴容操作
// (2)當數組長度大於等於最小樹化容量閾值時,將鏈表轉爲紅黑樹
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))))
// 鏈表中元素的key與傳入的key相同時,返回
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
// 4、將節點中的value 設爲新值
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
// 5、當集合元素數量大於閾值時,進行集合擴容操作
resize();
afterNodeInsertion(evict);
return null;
}