【北京】 IT技術人員面對面試、跳槽、升職等問題,如何快速成長,獲得大廠入門資格和升職加薪的籌碼?與大廠技術大牛面對面交流,解答你的疑惑。《從職場小白到技術總監成長之路:我的職場焦慮與救贖》活動鏈接:碼客
原文鏈接:https://juejin.im/post/5dc37979f265da4d307f1951
前言
HashMap作爲java中最常用的集合類之一,雖然在平時工作中經常要使用它,但是對於它的實現原理一直只是停留在從網上各處蒐集的"哈希表+鏈表+紅黑樹"的概念中,對於它具體的實現原理只是半知半解。因此死磕了下它的源碼,現對主要源碼進行註釋並加了個人的一些理解分享出來,共勉之。(源碼基於jdk1.8)
HashMap簡介
HashMap是一個可以保存key-value鍵值對的集合類,它的內部存儲結構是一個哈希表(數組),每個節點存放的是一個元素,這個元素可能是唯一元素,也可能只是一個鏈表的頭節點,或者紅黑樹的根節點,詳見下圖:
紅黑樹簡介
紅黑樹是一個大致平衡的二叉排序樹,它有5個性質:
-
每個結點非黑即紅
-
根結點是黑的
-
每個葉結點(葉結點即指樹尾端NIL指針或NULL結點)都是黑的
-
如果一個結點是紅的,那麼它的兩個兒子都是黑的
- 對於任一結點而言,其到葉結點樹尾端NIL指針的每一條路徑都包含相同數目的黑結點
正是這5條性質保證了紅黑樹的一個特點:從根節點到葉節點最長路徑不會超過最短路徑的兩倍,實現基本平衡。因篇幅有限,更多與紅黑樹相關內容就不贅述了。
API介紹文檔解讀
閱讀源碼前,根據網上大神的意見,先花時間啃了下hashmap的整體英文介紹,發現之後再閱讀源碼確實有很大的幫助,簡單翻譯了下類的介紹:
(1).hashmap與hashtable大致相同,除了它是非線程安全的,並且鍵值對允許爲空外;
(2).hashmap不保證元素的有序性,也不保證元素的順序隨着時間的推移不發生變化;
(3).如果迭代性能很重要,則不要將初始容量設置得太高(或負載因子太低);
(4).負載因子是作爲哈希表擴容的一個參考依據,當已使用的容量佔總容量達到負載因子時,開始拓展哈希表容量,大約拓展兩倍;默認負載因子爲0.75。
(5).創建時,在設置初始容量時,應考慮下預期容量和負載因子,以便最小化重新散列操作的次數;
(6).如果初始容量大於最大容量除以負載因子,則不會進行重新加載操作;
(7).如果hashmap要存儲大量數據時,初始化足量大的容量來存儲比自動拓展效率更快;
(8).使用具有相同hashcode的鍵值,容易降低hashmap的性能;爲了降低這個的影響,如果key實現了Comparable,可以使用鍵之間的比較順序來幫助打破關係;
(9).hashmap是非同步的,如果多個線程同時訪問數據,並且至少有一個線程在結構上修改了,則必須在外部進行同步(結構修改是添加和刪除操作,僅修改已存在鍵的值不少結構修改);
(10).實現同步的一種方法可以使用同步容器:Map m = Collections.synchronizedMap(new HashMap(...));
(11).如果在創建迭代器之後對hashmap進行結構修改,除了迭代器自己的remove方法外,迭代器都將拋出ConcurrentModifycationException;這樣做的原因是在併發修改的情況下,讓迭代器快速而乾淨地失敗,而不是在未來不確定的時間冒不確定的風險。
源碼解析
全部屬性
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
//序列號
private static final long serialVersionUID = 362498820763181265L;
// 默認的初始容量,即16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
// 最大容量,即2的31次方
static final int MAXIMUM_CAPACITY = 1 << 30;
// 默認的負載因子大小
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 當桶(bucket)上的結點數大於這個值時會轉成紅黑樹
static final int TREEIFY_THRESHOLD = 8;
// 當桶(bucket)上的結點數小於這個值時會把紅黑樹樹轉爲鏈表
static final int UNTREEIFY_THRESHOLD = 6;
// 桶中結構轉化爲紅黑樹對應的table的最小大小
static final int MIN_TREEIFY_CAPACITY = 64;
// 存儲元素的數組,總是2的冪次倍
transient Node<k,v>[] table;
// 存放具體元素的集
transient Set<map.entry<k,v>> entrySet;
// 已存放元素的個數,它是小於等於哈希表的長度的。
transient int size;
// 每次擴容和更改map結構的計數器,用於迭代時若結構發送變化就拋出異常
transient int modCount;
// 擴容閾值,當實際大小(容量*負載因子)超過閥值時,會進行擴容
int threshold;
// 負載因子
final float loadFactor;
}
構造方法
// 初始容量+負載因子
public HashMap(int initialCapacity, float loadFactor) {
// 初始容量不能小於0,否則報錯
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
// 初始容量大於最大值時,置爲最大值
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
// 填充因子不能小於或等於0,且不能爲非數字
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
// 初始化填充因子
this.loadFactor = loadFactor;
// 初始化threshold大小,實現如下
this.threshold = tableSizeFor(initialCapacity);
}
// 返回大於initialCapacity的最小的二次冪數值。比如輸入容量爲30,則返回32作爲真實容量
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;
}
// 初始容量+默認負載因子
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
// 無參構造,使用默認負載因子
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
// 使用相同實現的Map構造hashmap
public HashMap(Map<? extends K, ? extends V> m) {
// 默認負載因子
this.loadFactor = DEFAULT_LOAD_FACTOR;
// 將制定的Map元素插入到新的hashmap中
putMapEntries(m, false);
}
擴容方法-resize()
說明
- 將容量擴容2倍,同時將閥值threshold擴容兩倍
- 擴容後,需要將原哈希表中的數據複製到新哈希表中,複製時,根據元素類型使用不同的賦值方式
- 因爲擴容後,key的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;
}
//擴容兩倍後新容量小於最大容量且老容量大於默認基本容量(也就是16)
//這裏開始有點疑惑:爲啥不校驗容量擴爲2倍後的大小,不怕擴容後超過最大容量嗎。後來想到,hashmap的容量本來就是2的n次冪的,前面校驗了擴容前的容量是小於最大容量的,所以這次擴容最多出現等於最大容量的情況。
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 如果哈希表爲空,但是閾值大於0,則置哈希表容量爲閾值
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;
//如果當前節點只有一個元素(即無鏈表或者紅黑樹),直接複製元素
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
//如果元素爲紅黑樹類型,則添加到紅黑樹中
else if (e instanceof TreeNode)
// 執行紅黑樹調整(split在下面說明)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
//節點的元素鏈表保持順序
else { // preserve order
//lohead指low低位的頭結點,loTail表示低位的尾結點
Node<K,V> loHead = null, loTail = null;
//hohead指low低位的頭結點,hoTail表示低位的尾結點
Node<K,V> hiHead = null, hiTail = null;
//用來表示下一個結點
Node<K,V> next;
do {
next = e.next;
/*
舉個栗子:
odlCap爲16,則減1後爲: 000000 1111
key1的hash值爲: 110000 1010
key2的hash值爲: 110001 1010
容量拓展之後,newCap減1後爲:000001 1111
所以key2的hash值與容量計算出來的位置改變了,因此需要調整key2的數據到高位部分去
*/
//元素的hash值與舊容量按位與,如果結果等於0則表示繼續保持當前位置,不需要調整位置
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;
//使用j+oldCap將元素移動到高位
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
//擴容時對紅黑樹的調整,可能會出現紅黑樹轉鏈表,或者鏈表轉紅黑樹的情況
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
//獲取當前元素
TreeNode<K,V> b = this;
// Relink into lo and hi lists, preserving order
TreeNode<K,V> loHead = null, loTail = null;
TreeNode<K,V> hiHead = null, hiTail = null;
int lc = 0, hc = 0;
從根節點開始遍歷紅黑樹,統計出需要放到低位和需要移動到高位的元素個數,以便下面能通過個數重新平衡紅黑樹或者轉換爲鏈表
for (TreeNode<K,V> e = b, next; e != null; e = next) {
next = (TreeNode<K,V>)e.next;
e.next = null;
if ((e.hash & bit) == 0) {
if ((e.prev = loTail) == null)
loHead = e;
else
loTail.next = e;
loTail = e;
++lc;
}
else {
if ((e.prev = hiTail) == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
++hc;
}
}
//元素需要放到哈希表低位的處理
if (loHead != null) {
//如果元素個數小於等於紅黑樹轉鏈表的閥值時,進行轉鏈表操作
if (lc <= UNTREEIFY_THRESHOLD)
tab[index] = loHead.untreeify(map);
else {//不需要轉換鏈表
//將根節點放入哈希表首元素
tab[index] = loHead;
//判斷是否有需要移動到高位的,如果有則需要重新平衡紅黑樹,沒有的話則說明紅黑樹元素個數不變,位置也不需要調整了
if (hiHead != null) // (else is already treeified)
loHead.treeify(tab);
}
}
//元素需要放到哈希表高位的處理,操作跟上述差不多,只不過是在哈希表高位進行操作
if (hiHead != null) {
if (hc <= UNTREEIFY_THRESHOLD)
tab[index + bit] = hiHead.untreeify(map);
else {
tab[index + bit] = hiHead;
if (loHead != null)
hiHead.treeify(tab);
}
}
}
紅黑樹與鏈表之間轉換--treeify()和untreeify()
/*
1.將鏈表中的元素逐個添加到創建的紅黑樹中;
2.創建紅黑樹時,元素的排序優先級爲:key的hash值 > 實現Comparable接口的compareTo() > 強制比較對象生成的hash值方法-tieBreakOrder();
3.每添加一個元素時,通過balanceInsertion()方法保證紅黑樹的平衡;
*/
final void treeify(Node<K,V>[] tab) {
TreeNode<K,V> root = null;
//循環遍歷雙向鏈表節點,組成紅黑樹
for (TreeNode<K,V> x = this, next; x != null; x = next) {
//遍歷下一個節點
next = (TreeNode<K,V>)x.next;
//初始化左右節點爲空
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;
//首先根據hash值排序
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
//當出現hash衝突,key沒有實現Comparable接口,或者實現了Comparable接口但是還無法區分順序時,使用終極PK方法tieBreakOrder決出順序
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0)
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);
}
/*將紅黑樹轉換爲鏈表
因爲紅黑樹的TreeNode節點包含了鏈表屬性,所以直接通過鏈表的方式遍歷紅黑樹的節點,並整合到新的鏈表上
*/
final Node<K,V> untreeify(HashMap<K,V> map) {
Node<K,V> hd = null, tl = null;
//循環遍歷將紅黑樹中的每個元素取出來並串聯成一個單向鏈表,返回頭節點
for (Node<K,V> q = this; q != null; q = q.next) {
Node<K,V> p = map.replacementNode(q, null);
if (tl == null)
hd = p;
else
tl.next = p;
tl = p;
}
return hd;
}
紅黑樹保證平衡方法--balanceInsertion()
-
紅黑樹保持平衡的方法其實就是CLR中算法的實現;
- 主要使用的是變色和旋轉(左旋轉和右旋轉)來保證紅黑樹的平衡
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父父節點
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) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateLeft(root, xpp);
}
}
}
}
}
}
新增元素--put()
操作流程:
- 根據key的hash值與哈希表的長度減1後的值進行按位與操作得出元素將插入哈希表的位置
- 如果已存在相同key時,則直接覆蓋值value
- 根據元素的類型執行不同的值插入操作,比如紅黑樹插入還要保證平衡,鏈表則要遍歷是否已存在相同key,當元素個數達到一定數量時還要轉換爲紅黑樹
- 紅黑樹插入完成後可能根節點會發生變化,因此需要保證將根節點放在哈希表的首個元素
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;
//哈希表爲空或者表長度爲0,則拓展哈希表
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
/*
使用key的hash值與哈希表長度按位與計算出元素位置,判斷當前位置上是否有值,若沒有則直接將元素放入,否則進一步判斷
*/
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//若key已存在,則更新value值
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);
//如果鏈表上元素個數達到了轉換數的閾值(默認6)時,將鏈表轉換爲紅黑樹
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
//執行鏈表轉紅黑樹操作
treeifyBin(tab, hash);
break;
}
//如果鍵值已存在則直接返回(因爲之前e= p.next()時已經取到了舊值)
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
//與前面的e= p.next()組成循環遍歷
p = e;
}
}
//e!=null表示存在key相同的元素
if (e != null) { // existing mapping for key
V oldValue = e.value;
//存在相同key時,判斷是否需要覆蓋值value
if (!onlyIfAbsent || oldValue == null)
e.value = value;
//回調函數,hashmap中沒有實現,提供給linkedHashMap使用的
afterNodeAccess(e);
return oldValue;
}
}
//結構修改次數增加,迭代時檢查發現此值變了則拋出ConcurrentModificationException異常
++modCount;
//哈希表鍵值對數量增加,若超過閾值時則進行擴容
if (++size > threshold)
resize();
//回調函數,hashmap中沒有實現,提供給linkedHashMap使用的
afterNodeInsertion(evict);
return null;
}
/**
* Tree version of putVal.紅黑樹的插入方法
*/
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;
/*
因爲hashmap中的紅黑樹是根據key的hash值來排序的,所以先判斷新插入的key的hash值與當前父節點hash值
*/
//hash值小於父節點哈希值,取左節點
if ((ph = p.hash) > h)
dir = -1;
//hash值大於父節點哈希值,取右節點
else if (ph < h)
dir = 1;
//執行到此說明hash值相等,繼續比較鍵值是否相等,若相等則說明已存在相同鍵值,故直接返回當前節點的位置
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
//hash相等,但是key不相等
else if ((kc == null &&
//key未實現了Comparable接口
(kc = comparableClassFor(k)) == null) ||
//或者key實現了Comparable接口但是比較結果返回爲0,說明還是無法判斷出key的順序,此時產生了hash碰撞
(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;
}
//hash相等,key不相等,並且key沒有實現Comparable接口,保持一致的處理規則,也就是想辦法統一的排序規則,以便繼續往下遍歷
dir = tieBreakOrder(k, pk);
}
//備份當前節點
TreeNode<K,V> xp = p;
//若遍歷完紅黑樹,還是沒有找到相同key的結點,則進行新插入操作
if ((p = (dir <= 0) ? p.left : p.right) == null) {
/*
備份當前節點的下一個節點:相當於在鏈表的兩個節點a,b之間插入c時,先備份a.next,然後將a.next指向c,最後再將b.prev指向c
這些操作是給LinkedHashMap預留的
*/
Node<K,V> xpn = xp.next;
//創建新節點
TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
//根據之前比較hash值結果,將新節點放到的當前節點的左子節點或者右子節點
if (dir <= 0)
xp.left = x;
else
xp.right = x;
//將當前節點的next指向新節點
xp.next = x;
//設置新節點的父節點和前驅節點爲當前節點
x.parent = x.prev = xp;
//如果當前結點還有後繼節點時,將新節點作爲它的前驅
if (xpn != null)
((TreeNode<K,V>)xpn).prev = x;
//重排紅黑樹使其保證平衡(調用balanceInsertion方法實現,實現代碼改編自CLR-公共語言運行庫,使用變色和左右旋轉的原理),並將root節點放到哈希表的首元素
moveRootToFront(tab, balanceInsertion(root, x));
return null;
}
}
}
//將鏈表轉紅黑樹
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//如果哈希表爲空或哈希表長度小於最小允許轉爲紅黑樹的長度時,先進行擴容處理(因爲一般由於hash表長度太小時,更容易出現hash衝突,此時通過擴容解決更方便,性能也更高)
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
//取出當前hash值對應的哈希表位置
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);
}
}
刪除元素-remove()
- 刪除操作主要是要先獲取到該元素的節點位置,獲取方法根據不同的類型使用不同的方式:鏈表循環遍歷,紅黑樹使用遞歸遍歷
- 只有一個節點時,直接刪除即可,鏈表則遍歷後找到元素並刪除
- 紅黑樹上的節點刪除後需要根據情況調整平衡,調整的方式與插入類似
public V remove(Object key) {
Node<K,V> e;
//如果找到元素則返回元素的值value,否則返回null
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;
//哈希表不爲空+根據hash計算出的哈希表位置有元素時繼續
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;
//哈希表首元素的key與所刪除的key相等時,直接找到該元素
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;
//結構化調整次數加1,鍵值對總個數減1
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
//紅黑樹刪除元素執行方法
final void removeTreeNode(HashMap<K,V> map, Node<K,V>[] tab,
boolean movable) {
int n;
//哈希表爲空時直接返回
if (tab == null || (n = tab.length) == 0)
return;
int index = (n - 1) & hash;
TreeNode<K,V> first = (TreeNode<K,V>)tab[index], root = first, rl;
TreeNode<K,V> succ = (TreeNode<K,V>)next, pred = prev;
//前驅節點爲空時,說明要刪除元素是哈希表首元素,此時將首元素指定下一個元素(實現刪除)
if (pred == null)
tab[index] = first = succ;
//前驅節點不爲空,將刪除節點的前驅指向後繼(實現刪除)
else
pred.next = succ;
//後繼不爲空,則將刪除節點的後繼的前驅指向刪除節點的前驅(其實就是a<->b<->c,要刪除b,變成a<->c)
if (succ != null)
succ.prev = pred;
//該位置沒有元素時直接返回
if (first == null)
return;
//刪除節點不爲根節點時找到根節點
if (root.parent != null)
root = root.root();
//根節點爲空 或 根節點右節點爲空 或 根節點左節點爲空 或根節點左節點的左節點爲空時,將紅黑樹變爲鏈表並返回(說明刪除元素後元素太少)
if (root == null || root.right == null ||
(rl = root.left) == null || rl.left == null) {
tab[index] = first.untreeify(map); // too small
return;
}
//初始化,p是刪除節點,pl是左節點,pr是右節點,replacement是要移動的子節點
TreeNode<K,V> p = this, pl = left, pr = right, replacement;
//刪除節點有左右兩個節點
if (pl != null && pr != null) {
TreeNode<K,V> s = pr, sl;
//找到刪除節點的右節點的左節點
while ((sl = s.left) != null) // find successor
s = sl;
//交換刪除節點和右節點的左節點的顏色
boolean c = s.red; s.red = p.red; p.red = c; // swap colors
TreeNode<K,V> sr = s.right;
TreeNode<K,V> pp = p.parent;
if (s == pr) { // p was s's direct parent
p.parent = s;
s.right = p;
}
else {
TreeNode<K,V> sp = s.parent;
if ((p.parent = sp) != null) {
if (s == sp.left)
sp.left = p;
else
sp.right = p;
}
if ((s.right = pr) != null)
pr.parent = s;
}
p.left = null;
if ((p.right = sr) != null)
sr.parent = p;
if ((s.left = pl) != null)
pl.parent = s;
if ((s.parent = pp) == null)
root = s;
else if (p == pp.left)
pp.left = s;
else
pp.right = s;
if (sr != null)
replacement = sr;
else
replacement = p;
}
//刪除節點只有左節點
else if (pl != null)
replacement = pl;
//刪除節點只有右節點
else if (pr != null)
replacement = pr;
//刪除節點是葉節點
else
replacement = p;
//刪除節點非葉節點時,將它的子節點連接上它的父節點
if (replacement != p) {
TreeNode<K,V> pp = replacement.parent = p.parent;
if (pp == null)
root = replacement;
else if (p == pp.left)
pp.left = replacement;
else
pp.right = replacement;
p.left = p.right = p.parent = null;
}
//刪除節點後進行紅黑樹平衡處理,原理差不多,使用變色和旋轉
TreeNode<K,V> r = p.red ? root : balanceDeletion(root, replacement);
//刪除節點是葉子節點,則解除該節點的所有樹相關關聯
if (replacement == p) { // detach
TreeNode<K,V> pp = p.parent;
p.parent = null;
if (pp != null) {
if (p == pp.left)
pp.left = null;
else if (p == pp.right)
pp.right = null;
}
}
//根據標識決定是否將根節點轉移到哈希表首元素
if (movable)
moveRootToFront(tab, r);
}
查找元素--get()
思路基本差不多:
- 先根據hash值與哈希表容量按位與得到位置
- 根據節點類型使用不同的遍歷方式:鏈表用循環遍歷,紅黑樹用遞歸遍歷
public V get(Object key) {
Node<K,V> e;
//找到返回元素值,找不到返回null
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
//獲取元素實現方法
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//哈希表不爲空且當前位置元素不爲空時繼續
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//檢查第一個節點是否爲查找的目標
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//該位置有鏈表或者紅黑樹
if ((e = first.next) != null) {
//節點爲紅黑樹時,執行紅黑樹的查找元素方法
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//節點爲鏈表時,遍歷鏈表獲取元素
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
//紅黑樹查找節點方法
final TreeNode<K,V> getTreeNode(int h, Object k) {
return ((parent != null) ? root() : this).find(h, k, null);
}
/*遞歸查找紅黑樹,獲取指定節點
1.根據hash值順序進行遍歷;
2.若hash值存在相等時,則根據key實現的Comparable接口來獲取順序繼續遍歷;
3.如果以上都沒有得出遍歷順序則統一遞歸調用find從右節點繼續遍歷;
*/
final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
TreeNode<K,V> p = this;
do {
int ph, dir; K pk;
TreeNode<K,V> pl = p.left, pr = p.right, q;
//hash值小於當前遍歷的節點hash值,下一次比較它們的左子樹
if ((ph = p.hash) > h)
p = pl;
//hash值大於當前遍歷的節點hash值,下一次比較它們的右子樹
else if (ph < h)
p = pr;
//hash值相等且key相等時直接返回節點
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
//左節點爲空則遍歷右節點
else if (pl == null)
p = pr;
//右節點爲空則遍歷左節點
else if (pr == null)
p = pl;
//key的類實現了Comparable接口則比較根據compareTo方法比較大小獲取順序
else if ((kc != null ||
(kc = comparableClassFor(k)) != null) &&
(dir = compareComparables(kc, k, pk)) != 0)
p = (dir < 0) ? pl : pr;
//若上述操作都沒有得出遍歷順序時,則統一從右結點開始繼續遞歸遍歷
else if ((q = pr.find(h, k, kc)) != null)
return q;
else
p = pl;
} while (p != null);
return null;
}
迭代方法--entrySet()
- entrySet迭代方法相比keySet來說性能相對而言要快點,因爲keySet是先獲取key,然後再根據key調用前面介紹的get()方法獲取值,get方法會有一定的性能開銷。而entrySet是直接返回key-value的Set集合
- 迭代其實就是藉助於每個hashmap的節點都有next節點的鏈表結構,相當於就是循環地遍歷鏈表
- 通過迭代的源碼也可以看出迭代不保證與插入順序一致的原因:因爲迭代是從哈希表的第一個存儲單元開始,逐個遍歷每個單元的節點或節點鏈表或者紅黑樹,而插入的時候是根據key的hash值從哈希表中任一位置插入的
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es;
//迭代類可以複用,實際使用的是內部的EntrySet類
return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}
//內部迭代類
final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
//內部實現迭代方法,返回的是內部的迭代類EntryIterator
public final Iterator<Map.Entry<K,V>> iterator() {
return new EntryIterator();
}
}
final class EntryIterator extends HashIterator
implements Iterator<Map.Entry<K,V>> {
//主要通過該next方法獲取下一個元素
public final Map.Entry<K,V> next() {
return nextNode();
}
}
//實際迭代的內部類
abstract class HashIterator {
Node<K,V> next; // next entry to return 下一個節點
Node<K,V> current; // current entry 當前節點
int expectedModCount; // for fast-fail 預期的結構性修改次數,避免遍歷期間進行結構性修改(插入和刪除操作)
int index; // current slot 當前位置
HashIterator() {
//備份結構修改次數,作爲遍歷時的預期
expectedModCount = modCount;
Node<K,V>[] t = table;
current = next = null;
index = 0;
//遍歷哈希表,定位到第一個有元素的位置
if (t != null && size > 0) { // advance to first entry
do {} while (index < t.length && (next = t[index++]) == null);
}
}
//判斷是否還有非空元素
public final boolean hasNext() {
return next != null;
}
//獲取下一個節點
final Node<K,V> nextNode() {
Node<K,V>[] t;
//取下一個元素
Node<K,V> e = next;
//如果在迭代期間有結構性修改則拋出異常
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
//元素爲空時拋出異常
if (e == null)
throw new NoSuchElementException();
//保證下一次取到的元素不爲空
if ((next = (current = e).next) == null && (t = table) != null) {
do {} while (index < t.length && (next = t[index++]) == null);
}
return e;
}
//遍歷期間可以刪除元素操作方法
public final void remove() {
Node<K,V> p = current;
if (p == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
current = null;
K key = p.key;
//調用刪除元素的方法(包含紅黑樹的平衡調整)
removeNode(hash(key), key, null, false, false);
//更新預期的結構性變化次數
expectedModCount = modCount;
}
}
其他方法
/*檢查對象的class是否實現了Comparable接口
1.主要檢查key鍵的類class是否實現了Comparable接口,而且是要實現的是參數化的接口,比如Comparable<String>;
2.String類是最常見作爲key的類,且它有完整的Comparable實現,所以該方法爲String類開了綠燈;
*/
static Class<?> comparableClassFor(Object x) {
//對象要求是Comparable的實例
if (x instanceof Comparable) {
Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
//對象爲string時,開綠燈直接pass(因爲String類最常用作key,且它對Comparable有具體的實現)
if ((c = x.getClass()) == String.class) // bypass checks
return c;
//獲取對象的所有實現接口
if ((ts = c.getGenericInterfaces()) != null) {
for (int i = 0; i < ts.length; ++i) {
/*
1.所實現的接口是參數化類型,比如Colloction<String>
2.該接口參數化類型的頭部是Comparable,例如Collocation<String>的頭部是Collocation
3.該接口的參數化類型只有一個,例如Collocation<String>只有String一個類型;
4.該接口的參數化類型爲對象的class本身;例如Integer實現了Comparable<Integer>中的參數就是Integer;
符合以上四個條件表示該對象的類實現了Comparable<對象的class>接口
*/
if (((t = ts[i]) instanceof ParameterizedType) &&
((p = (ParameterizedType)t).getRawType() ==
Comparable.class) &&
(as = p.getActualTypeArguments()) != null &&
as.length == 1 && as[0] == c) // type arg is c
return c;
}
}
}
return null;
}
/*將根節點放到哈希表中的首個元素
主要就是確保根節點是哈希表首個元素,調整時同步調整它們的前驅和後繼
*/
static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) {
int n;
//保證root和哈希表不爲空
if (root != null && tab != null && (n = tab.length) > 0) {
//用root的hash值與哈希表長度做按位與操作得出存儲位置
int index = (n - 1) & root.hash;
//獲取當前位置的元素
TreeNode<K,V> first = (TreeNode<K,V>)tab[index];
//若根節點不是當前hash位置的首元素則進行調整
if (root != first) {
Node<K,V> rn;
//將當前hash位置首元素放root節點
tab[index] = root;
//備份root的前驅節點
TreeNode<K,V> rp = root.prev;
//將root後繼節點的前驅指向root的前驅,類似a->b->c,rp是a,root是b.rn是c,調整爲a->c
if ((rn = root.next) != null)
((TreeNode<K,V>)rn).prev = rp;
//root前驅不爲空時,將root前驅指向root後繼
if (rp != null)
rp.next = rn;
//當前hash位置上的原元素不爲空,則將其作爲root的後繼
if (first != null)
first.prev = root;
root.next = first;
root.prev = null;
}
assert checkInvariants(root);
}
}
總結
本文作者:本文是作者第一次完整地閱讀源碼,雖然過程很枯燥,但是堅持下來後發現學習到的東西確實比直接看別人總結出來的結論要深刻,而且更透徹了。本文作爲開篇,以後有源碼閱讀也會記錄下來,作爲一種學習筆記共勉。
(想自學習編程的小夥伴請搜索圈T社區,更多行業相關資訊更有行業相關免費視頻教程。完全免費哦!)