基本屬性
// 初始化容量,必須要2的n次冪
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// 負載因子默認值
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 需要從鏈表轉換爲紅黑樹時,鏈表節點的最小長度
// 依據泊松分佈,單個鏈表超過8個元素的機率十分小了,所以爲8;
static final int TREEIFY_THRESHOLD = 8;
// 轉換爲紅黑樹時數組的最小容量
static final int MIN_TREEIFY_CAPACITY = 64;
// resize操作時,紅黑樹節點個數小於6則轉換爲鏈表。
static final int UNTREEIFY_THRESHOLD = 6;
// HashMap閾值,用於判斷是否需要擴容(threshold = 容量*loadFactor)
int threshold;
// 負載因子
final float loadFactor;
// 鏈表節點
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
}
// 保存數據的數組
transient Node<K,V>[] table;
// 紅黑樹節點
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent; // red-black tree links
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red;
}
hash()
高16位於低16位異或,降低了hash衝突機率
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
tableSizeFor()
構造器可以傳入初始容量參數,如果不是2的冪,會被轉化成大於所傳參數最接近的2的冪。
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
put()
- 第一次添加元素時,table爲null,初始化table數組
- 計算對應的數組下標
(n - 1) & hash
- 如果這個槽還沒有數據,直接插入
- 如果key已經存在,替換value
- 如果該鏈表已經轉換成紅黑樹,在樹中插入元素
- 如果是鏈表,遍歷鏈表,遇到相同key,替換value,否則在鏈表尾部插入元素(尾插法,防止出現死循環)
- 如果鏈表長度>8,轉換爲紅黑樹
- 最後判斷是否超過閾值需要擴容
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 1. table 爲 null,初始化哈希桶數組
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 2. 計算對應的數組下標 (n - 1) & hash
if ((p = tab[i = (n - 1) & hash]) == null)
// 3. 這個槽還沒有插入過數據,直接插入
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
// 4. 節點 key 存在,直接覆蓋 value
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 5. 該鏈轉成了紅黑樹
else if (p instanceof TreeNode) // 在樹中插入
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
// 6. 該鏈是鏈表
else {
for (int binCount = 0; ; ++binCount) {
// 遍歷找到尾節點插入
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
// 鏈表長度大於 8 轉爲紅黑樹
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 遍歷的過程中,遇到相同 key 則覆蓋 value
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;
// 7. 超過最大容量,擴容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
resize()
因爲擴容的新容量爲舊容量的兩倍,也就是二進制向左移一位,這樣再進行(n - 1) & hash
計算分配桶的時候,就會有兩種情況,一種是元素索引不變,一種是元素索引變成原索引+舊容量。
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) {
// 超過最大值,不在擴容
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}// 否則擴大爲原來的 2 倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
// 初始化時,threshold 暫時保存 initialCapacity 參數的值
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 計算新的 resize 上限
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
// 拆鏈表,拆成兩個子鏈表並保持原有順序
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;
}
// 原位置偏移 oldCap 的子鏈表
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;
}
treeifyBin()
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
// 如果哈希桶容量小於樹化的最小容量,優先進行擴容
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do { // 將普通節點轉爲樹形節點
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
// 把原來的單鏈錶轉成了雙向鏈表
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab); // 將鏈表轉爲紅黑樹
}
}
TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
return new TreeNode<>(p.hash, p.key, p.value, next);
}