putVal() 方法解析
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 如果存儲元素的table爲空,則進行必要字段的初始化
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length; // 獲取長度(16)
// 如果根據hash值獲取的結點爲空,則新建一個結點
if ((p = tab[i = (n - 1) & hash]) == null) // 此處 & 代替了 % (除法散列法進行散列)
tab[i] = newNode(hash, key, value, null);
// 這裏的p結點是根據hash值算出來對應在數組中的元素
else {
Node<K,V> e; K k;
// 如果新插入的結點和table中p結點的hash值,key值相同的話
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
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);
// 鏈表長度大於8時,將鏈表轉紅黑樹
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
p = e;
}
}
// 如果存在這個映射就覆蓋
if (e != null) { // existing mapping for key
V oldValue = e.value;
// 判斷是否允許覆蓋,並且value是否爲空
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e); // 回調以允許LinkedHashMap後置操作
return oldValue;
}
}
++modCount; // 更改操作次數
if (++size > threshold) // 大於臨界值
// 將數組大小設置爲原來的2倍,並將原先的數組中的元素放到新數組中
// 因爲有鏈表,紅黑樹之類,因此還要調整他們
resize();
// 回調以允許LinkedHashMap後置操作
afterNodeInsertion(evict);
return null;
}
resize()解析:
//初始化或者擴容之後元素調整
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) { // 如果原table不爲空
// 如果數組長度達到最大值,則修改臨界值爲Integer.MAX_VALUE
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 下面就是擴容操作(2倍)
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
// threshold也變爲二倍
newThr = oldThr << 1;
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // threshold爲0,則使用默認值
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) { // 如果臨界值還爲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;
}
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;
}
putTreeVal()解析:
// 紅黑樹插入
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
int h, K k, V v) {
Class<?> kc = null;
boolean searched = false;
TreeNode<K,V> root = (parent != null) ? root() : this; // 找Root
for (TreeNode<K,V> p = root;;) {
int dir, ph; K pk;
if ((ph = p.hash) > h) // 紅黑樹中根據hash值、key值找結點
dir = -1;
else if (ph < h)
dir = 1;
else if ((pk = p.key) == k || (k != null && k.equals(pk))) // 找到則返回此節點
return p;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
if (!searched) {
TreeNode<K,V> q, ch;
searched = true;
if (((ch = p.left) != null &&
(q = ch.find(h, k, kc)) != null) ||
((ch = p.right) != null &&
(q = ch.find(h, k, kc)) != null))
return q;
}
dir = tieBreakOrder(k, pk);
}
TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) { // 沒找到時
Node<K,V> xpn = xp.next;
TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn); // 創建一個結點
if (dir <= 0) // 比較
xp.left = x;
else
xp.right = x;
xp.next = x; // 插入
x.parent = x.prev = xp;
if (xpn != null)
((TreeNode<K,V>)xpn).prev = x;
moveRootToFront(tab, balanceInsertion(root, x)); // 調整
return null;
}
}
}
treeifyBin()解析
// 鏈表轉雙向鏈表操作
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
// 如果元素總個數小於64,則繼續進行擴容,結點指向調節
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);
}
}
treeify()解析
//將鏈表中每個值進行紅黑樹插入操作
final void treeify(Node<K,V>[] tab) {
TreeNode<K,V> root = null;
// TreeNode<K,V> x = this 相當於初始化了一個結點
for (TreeNode<K,V> x = this, next; x != null; x = next) {
next = (TreeNode<K,V>)x.next;
// 初始化Root
x.left = x.right = null;
if (root == null) {
x.parent = null;
x.red = false;
root = x;
}
else {
K k = x.key;
int h = x.hash;
Class<?> kc = null;
for (TreeNode<K,V> p = root;;) {
int dir, ph;
K pk = p.key;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((kc == null &&
// comparableClassFor(k) 返回 k 類型的比較器
(kc = comparableClassFor(k)) == null) ||
// compareComparables(kc, k, pk) 返回p,pk比較的結果
(dir = compareComparables(kc, k, pk)) == 0)
// tieBreakOrder(k, pk) 比較兩個hash碼
dir = tieBreakOrder(k, pk);
// 此處進行紅黑樹操作
TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
x.parent = xp;
if (dir <= 0)
xp.left = x;
else
xp.right = x;
// 平衡調節
root = balanceInsertion(root, x);
break;
}
}
}
}
// 確保給定的根是根結點
moveRootToFront(tab, root);
}
balanceInsertion()解析
// 插入後的平衡操作
static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
TreeNode<K,V> x) {
x.red = true;
for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
// 沒有結點時
if ((xp = x.parent) == null) {
x.red = false;
return x;
}
// 只有兩層的樹
else if (!xp.red || (xpp = xp.parent) == null)
return root;
// 左子樹插入
if (xp == (xppl = xpp.left)) {
if ((xppr = xpp.right) != null && xppr.red) {
xppr.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
}
else {
if (x == xp.right) {
root = rotateLeft(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateRight(root, xpp);
}
}
}
}
// 右子樹插入
else {
// 祖父結點不爲空,並且顏色爲紅色時
if (xppl != null && xppl.red) {
xppl.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
}
else {
// 左子樹插入
if (x == xp.left) {
root = rotateRight(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
// x 的父親結點設置成黑色
xp.red = false;
if (xpp != null) {
// x的祖父結點設置成紅色
xpp.red = true;
// 左旋
root = rotateLeft(root, xpp);
}
}
}
}
}
}
rotateLeft()解析
配圖:
// 紅黑樹的左旋操作
static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
TreeNode<K,V> p) {
// r(right) 指的是調整點的右子樹根結點
// pp(parentparent) 是p的祖父結點
// rl(rigthleft) 是p的叔父結點
TreeNode<K,V> r, pp, rl;
if (p != null && (r = p.right) != null) {
if ((rl = p.right = r.left) != null)
rl.parent = p;
if ((pp = r.parent = p.parent) == null)
(root = r).red = false;
else if (pp.left == p)
pp.left = r;
else
pp.right = r;
r.left = p;
p.parent = r;
}
return root;
}