1. put的實現
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;
//如果當前map中無數據,執行resize方法。並且返回n
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//如果要插入的鍵值對要存放的這個位置剛好沒有元素,那麼把他封裝成Node對象,放在這個位置上就完事了
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//否則的話,說明這上面有元素
else {
Node<K,V> e; K k;
//如果這個元素的key與要插入的一樣,那麼就替換一下,也完事。
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//1.如果當前節點是TreeNode類型的數據,執行putTreeVal方法
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//還是遍歷這條鏈子上的數據,跟jdk6沒什麼區別
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//2.完成了操作後多做了一件事情,判斷,並且可能執行treeifyBin方法
//長度是否達到閾值,需要把鏈表換成樹的形式
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 = 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;
}
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;
for (TreeNode<K,V> p = root;;) {
int dir, ph; K pk;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
// 如果發現紅黑樹某個節點的key和要put的相同,返回就可以了
return p;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
// hash相等,且key無法比較或者相等
if (!searched) {// 如果查找過沒有相同的節點,下次就不用再找了
TreeNode<K,V> q, ch;
searched = true;
// 雙空節點或者左子樹右子樹都沒有和這個key一樣的節點的時候就不會return q了。
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;
}
}
}
static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
TreeNode<K,V> x) {
//插入的節點必須是紅色的,除非是根節點
x.red = true;
//遍歷到x節點爲黑色,整個過程是一個上濾的過程
for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
// case 0.插入節點z爲根節點——這種情況好辦,直接染黑完事,我們不討論
if ((xp = x.parent) == null) {
x.red = false;
return x;
}
//如果xp的黑色就直接完成,最簡單的情況
//case 1.父節點爲黑色節點——這種情況最好辦,根本沒有破壞紅黑樹的五大性質,不需要做任何調整,我們不討論
else if (!xp.red || (xpp = xp.parent) == null)
return root;
//如果x的父節點是x父節點的左節點
if (xp == (xppl = xpp.left)) {
//x的父親節點的兄弟是紅色的(需要顏色翻轉)
// case 2.父節點爲紅色節點,叔節點也爲紅色
if ((xppr = xpp.right) != null && xppr.red) {
//x父親節點的兄弟節點置成黑色
xppr.red = false;
//父節點一樣是黑色
xp.red = false;
//祖父節點置成紅色
xpp.red = true;
//然後上濾(就是不斷的重複上面的操作)
x = xpp;
}
else {
//如果x是xp的右節點整個要進行兩次旋轉,先左旋轉再右旋轉
//case 3.父節點爲紅色節點,叔節點爲黑色節點,當前節點爲右孩子
if (x == xp.right) {
root = rotateLeft(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
// case 4.父節點爲紅色節點,叔節點爲黑色節點,當前節點爲左孩子
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) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateLeft(root, xpp);
}
}
}
}
}
}
2.remove的實現
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
// 先找出要刪除的節點node
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
// 如果是首節點
else if (node == p)
tab[index] = node.next;
else// 非首節點
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
TreeNode<K,V> x) {
for (TreeNode<K,V> xp, xpl, xpr;;) {
if (x == null || x == root)
return root;
else if ((xp = x.parent) == null) {
x.red = false;
return x;
}
//case 1 x是紅色的,是最容易解決的,直接染黑就是了。
else if (x.red) {
x.red = false;
return root;
}
else if ((xpl = xp.left) == x) {
// case 2 x的兄弟節點是紅色的,染黑兄弟節點,染紅父節點,左旋轉父節點,重置兄弟節點
if ((xpr = xp.right) != null && xpr.red) {
xpr.red = false;
xp.red = true;
root = rotateLeft(root, xp);
xpr = (xp = x.parent) == null ? null : xp.right;
}
if (xpr == null)
x = xp;
else {
// case 3 x的兄弟節點w是黑色的,而且w的兩個子節點都是黑色的
TreeNode<K,V> sl = xpr.left, sr = xpr.right;
if ((sr == null || !sr.red) &&
(sl == null || !sl.red)) {
xpr.red = true;
x = xp;
}
else {
// case 4 x的兄弟節點w是黑色的,w的左兒子是紅色的,w的右孩子是黑色的
if (sr == null || !sr.red) {
if (sl != null)
sl.red = false;
xpr.red = true;
root = rotateRight(root, xpr);
xpr = (xp = x.parent) == null ?
null : xp.right;
}
// case 5 x的兄弟節點w是黑色的,且w的右孩子是紅色的。
if (xpr != null) {
xpr.red = (xp == null) ? false : xp.red;
if ((sr = xpr.right) != null)
sr.red = false;
}
if (xp != null) {
xp.red = false;
root = rotateLeft(root, xp);
}
x = root;
}
}
}
// x是右節點情況,和左節點操作是對稱的,不討論
else { // symmetric
if (xpl != null && xpl.red) {
xpl.red = false;
xp.red = true;
root = rotateRight(root, xp);
xpl = (xp = x.parent) == null ? null : xp.left;
}
if (xpl == null)
x = xp;
else {
TreeNode<K,V> sl = xpl.left, sr = xpl.right;
if ((sl == null || !sl.red) &&
(sr == null || !sr.red)) {
xpl.red = true;
x = xp;
}
else {
if (sl == null || !sl.red) {
if (sr != null)
sr.red = false;
xpl.red = true;
root = rotateLeft(root, xpl);
xpl = (xp = x.parent) == null ?
null : xp.left;
}
if (xpl != null) {
xpl.red = (xp == null) ? false : xp.red;
if ((sl = xpl.left) != null)
sl.red = false;
}
if (xp != null) {
xp.red = false;
root = rotateRight(root, xp);
}
x = root;
}
}
}
}
}
3.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長度太大了,閾值就不管了,不再擴容。
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
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
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
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;
// 如果該位置只有一個節點,直接移過去心的tab就好了
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;
}
這裏的高低串說明一下,hashMap求某個hash值落在table哪個index的算法是hash & (cap - 1) ,因爲cap是2的倍數,也就是求hash有多少個1了。當發生擴總newCap是cap的兩倍。這時候rehash重定位會發生兩種情況:
1.情況1是hash1 & oldCap == 0,這裏假設某個key的hash值爲hash1,再次計算hash1的index時候公式爲hash1 & (newCap -1)。因爲(newCap -1)的最高位和oldCap的最高位是一樣的,都是1,這裏爲方便說明假設最高位爲第n位。hash1 & oldCap == 0說明hash1的第n位爲0,而(newCap -1)高於第n爲的也爲0,則hash1 & (newCap -1) == hash1 & (oldCap - 1)。總的來說,其實hash1 & oldCap == 0就說明了hash1和newCap 的第二高位對應的那位是0,意思是擴容後,這類型的hash所對應的index不變。
舉個例子,比如當oldCap = 10,newCap = 100,hash1 = 01 時。發生擴容前hash1的index爲hash & (oldCap - 1)= 01 & 01 = 1;發生擴容後hash1的index爲hash & (newCap - 1)= 01 & 011 = 1;
2.情況2是hash2 & oldCap !=0,這裏假設某個key的hash值爲hash2,就說明了hash2和newCap 的第二高位對應的那位是1,那麼hash2 & (newCap -1) == hash2 & (oldCap -1) + oldCap == hash2 & oldIndex + oldCap。
舉個例子,比如當oldCap = 10,newCap = 100,hash2 = 11 時。發生擴容前hash2的index爲
hash2 & (10 - 1) == 1;發生擴容後hash2的index爲hash2 & (100 - 1) = hash2 & (10 - 1) + 10 == 1 + 10 = 11