一、前言
- 隨着JDK(Java Developmet Kit)版本的更新,JDK1.8對HashMap底層的實現進行了優化,例如引入紅黑樹的數據結構和擴容的優化等。
HashMap:它根據鍵的hashCode值存儲數據,大多數情況下可以直接定位到它的值,因而具有很快的訪問速度,但遍歷順序卻是不確定的。 - HashMap最多隻允許一條記錄的鍵爲null,允許多條記錄的值爲null。
- HashMap非線程安全,即任一時刻可以有多個線程同時寫HashMap,可能會導致數據的不一致。如果需要滿足線程安全,可以用 Collections的synchronizedMap方法使HashMap具有線程安全的能力,或者使用ConcurrentHashMap。
- HasMap 的容量爲 2 的冪數,就是爲了數據的均勻分佈,減少 hash 衝突,畢竟hash衝突越大代表數組中的一個鏈就越大,這樣的話就會降低HashMap 的性能。
二、HashMap基礎
HashMap繼承了AbstractMap類,實現了Map,Cloneable,Serializable接口
//HashMap的容量,默認是16,擴容是爲2的冪即2倍進行擴容
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//閾值,閾值=容量*加載因子。每次擴容是的最大值,超過這個值就擴容。默認 12
int threshold;
//HashMap的加載因子,默認是0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//HashMap的容量是有上限的,必須小於1<<30,即1073741824。
//如果容量超出了這個數,則不再增長,且閾值會被設置爲Integer.MAX_VALUE,即永遠不會超出閾值了)。
static final int MAXIMUM_CAPACITY = 1 << 30;
//由線性鏈表轉化爲樹的閾值,默認值爲 8。桶中bin的數量超過該閾值,就由鏈表轉化爲樹。
static final int TREEIFY_THRESHOLD = 8;
//由樹轉化爲鏈表的閾值,默認值爲 6。當桶中bin的數量小於該閾值,就將樹轉化爲鏈表
static final int UNTREEIFY_THRESHOLD = 6;
//桶中bin 被樹化時,最小的hash表容量,默認爲 64 。
static final int MIN_TREEIFY_CAPACITY = 64;
//定義一個類型爲Node<K,V>的table數組
transient Node<K,V>[] table;
//table數組的長度
transient int size
//實際的加載因子, 在構造器中進行初始化
//如果創建HashMap時沒有指定loadFactor的大小則會初始化爲DEFAULT_INITIAL_CAPACITY的值
final float loadFactor;
//HashMap更改的次數
//用來作爲併發下判斷是否有其它線程修改了該HashMap,拋出ConcurrentModificationException
transient int modCount;
當HashMap中元素數超過容量*加載因子時,HashMap會進行擴容。
-
1.3、Node和Node鏈
HashMap類中的元素是Node類,翻譯過來就是節點,是定義在HashMap中的一個內部類,實現了Map.Entry接口。
static class Node<K,V> implements Map.Entry<K,V> {
//key的哈希值
final int hash;
//節點的key,類型和定義HashMap時的key相同
final K key;
//節點的value,類型和定義HashMap時的value相同
V value;
//該節點的下一節點
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
值得注意的是其中的next屬性,記錄的是下一個節點本身,也是一個Node節點,這個Node節點也有next屬性,記錄了下一個節點。而對於一個HashMap來說,只要明確記錄每個鏈表的第一個節點,就能順序遍歷鏈表上的所有節點。
-
1.4、TreeNode紅黑樹
當HashMap把鏈表轉爲紅黑樹的時候,原來的Node節點就會被轉爲TreeNode節點,TreeNode也是HashMap中定義的內部類,定義大概是這樣的:
static final class TreeNode<K,V> extends LinkedHashMap.LinkedHashMapEntry<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;
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}
final TreeNode<K,V> root() {
for (TreeNode<K,V> r = this, p;;) {
if ((p = r.parent) == null)
return r;
r = p;
}
}
//從節點移出元素
static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) {
int n;
if (root != null && tab != null && (n = tab.length) > 0) {
int index = (n - 1) & root.hash;
TreeNode<K,V> first = (TreeNode<K,V>)tab[index];
if (root != first) {
Node<K,V> rn;
tab[index] = root;
TreeNode<K,V> rp = root.prev;
if ((rn = root.next) != null)
((TreeNode<K,V>)rn).prev = rp;
if (rp != null)
rp.next = rn;
if (first != null)
first.prev = root;
root.next = first;
root.prev = null;
}
assert checkInvariants(root);
}
}
//查找元素
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;
if ((ph = p.hash) > h)
p = pl;
else if (ph < h)
p = pr;
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;
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;
}
...
}
可以看到,TreeNode繼承了LinkedHashMap的Entry,TreeNode節點在構造時,也指定了hash值,key,value,下一節點next,這些都是和Node相同的結構。
同時,TreeNode還保存了父節點parent, 左孩子left,右孩子right,上一節點prev,另外還有紅黑樹用到的red屬性。
紅黑樹是一種近似平衡的二叉查找樹,他並非絕對平衡,但是可以保證任何一個節點的左右子樹的高度差不會超過二者中較低的那個的一倍。
紅黑樹有這樣的特點:
- 1、每個節點要麼是紅色,要麼是黑色。
- 2、根節點必須是黑色。葉子節點必須是黑色NULL節點。
- 3、紅色節點不能連續。
- 4、對於每個節點,從該點至葉子節點的任何路徑,都含有相同個數的黑色節點。
- 5、能夠以O(log2(N))的時間複雜度進行搜索、插入、刪除操作。此外,任何不平衡都會在3次旋轉之內解決。
三、put 元素
- 1、hash值和table.length取模
取模的方法是(table.length - 1) & hash,算法直接捨棄了二進制hash值在table.length以上的位,因爲那些位都代表table.length的2的n次方倍數。(table.length - 1) & hash 位運算主要提高運算效率。
取模的結果就是Node將要放入table的下標。
比如,一個Node的hash值是5,table長度是4,那麼取餘的結果是1,也就是說,這個Node將被放入table[1]所代表的鏈表(table[1]本身指向的是鏈表的第一個節點)。
- 2、添加元素
如果此時table的對應位置沒有任何元素,也就是table[i]=null,那麼就直接把Node放入table[i]的位置,並且這個Node的next==null。
如果此時table對應位置是一個Node,說明對應的位置已經保存了一個Node鏈表,則需要遍歷鏈表,如果發現相同hash值則替換Node節點,如果沒有相同hash值,則把新的Node插入鏈表的末端,作爲之前末端Node的next,同時新Node的next==null。
如果此時table對應位置是一個TreeNode,說明鏈表被轉換成了紅黑樹,則根據hash值向紅黑樹中添加或替換TreeNode。(JDK1.8)
3、如果添加元素之後,Node鏈表的節點數超過了8個,則該鏈表會考慮轉爲紅黑樹。(JDK1.8)
5、如果添加元素之後,HashMap總節點數超過了閾值,則HashMap會進行擴容。
- 添加Value
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
- 計算hash值
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
- 判斷是否擴容或者轉換成紅黑樹
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)
//第一次put進入,創建數組並擴容數組個數爲 8
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
//table對應位置無節點,則創建新的Node節點放入對應位置。
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//table對應位置有節點,如果hash值匹配,則替換
e = p;
else if (p instanceof TreeNode)
//table對應位置有節點,如果table對應位置已經是一個TreeNode,
//不再是Node,也就說,table對應位置是TreeNode,
//表示已經從鏈表轉換成了紅黑樹,則執行插入紅黑樹節點的邏輯。
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
//創建Node節點,加到上個節點的next位置
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
//table對應位置有節點,且節點是Node(鏈表狀態,不是紅黑樹),所以加上根節點爲 8
//鏈表中節點數量大於TREEIFY_THRESHOLD = 8,則考慮變爲紅黑樹。
//實際上不一定真的立刻就變,table短的時候擴容一下也能解決問題,後面的代碼會提到
treeifyBin(tab, hash);
break;
}
//找到相等的key節點
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//key相等覆蓋邏輯
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
//更改次數加1
++modCount;
//HashMap中節點個數大於threshold,會進行擴容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
執行TreeNode#putTreeVal
添加紅黑樹節點
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
int h, K k, V v) {
// map 當前Hashmap對象
//tab Hashmap對象中的table數組
//h hash值
// K key
// V value
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;
// 根據hash值 判斷方向
if ((ph = p.hash) > h)
// 大於放左側
dir = -1;
else if (ph < h)
// 小於放右側
dir = 1;
// 如果key 相等 直接返回該節點的引用 外邊的方法會對其value進行設置
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
/**
*下面的步驟主要就是當發生衝突 也就是hash相等的時候
* 檢驗是否有hash相同 並且equals相同的節點。
* 也就是檢驗該鍵是否存在與該樹上
*/
//說明進入下面這個判斷的條件是 hash相同 但是equal不同
// 沒有實現Comparable<C>接口或者 實現該接口 並且 k與pk Comparable比較結果相同
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
//在左右子樹遞歸的尋找 是否有key的hash相同 並且equals相同的節點
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;
}
//說明紅黑樹中沒有與之equals相等的 那就必須進行插入操作
//打破平衡的方法的 分出大小 結果 只有-1 1
dir = tieBreakOrder(k, pk);
}
//下列操作進行插入節點
//xp 保存當前節點
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;
//將root移到table數組的i 位置的第一個節點
//插入操作過紅黑樹之後 重新調整平衡。
moveRootToFront(tab, balanceInsertion(root, x));
return null;
}
}
}
添加樹形節點,與添加雙鏈表節點個過程類似:
- 1、從root節點開始尋找 如果目標k.hash 小於 當前節點的 hash ,那麼到左樹尋找,大於那麼從右樹尋找。如果找到key相同並且equals相同的節點 p 那就直接返回。
- 2、如果hash相同 但是equal不同 進而通過Comparable接口,進行比較,如果比較的結果如果還是相等,則在左右子樹遞歸的尋找是否有與要插入的key equals相同的元素。如果有那麼直接return返回。
(也即是沒實現Comparable接口,大小由hash判定。實現了,則由Comparable接口的比較方法判定)- 3、如果遍歷完所有的節點 並未找到equals相同的節點。那就需要插入該新節點。必須分出大小,所以通過執行tieBreakOrder方法,該方法的返回值是-1,1。如果是-1則插入到左邊節點,1就插入到右邊節點。
- 4、插入完成之後,需要重新移動root節點 到table數組的i位置的第一個節點上 並且需重新平衡紅黑樹。
四、轉換紅黑樹
//大於8 轉調用換爲紅黑樹
static final int TREEIFY_THRESHOLD = 8;
//桶中bin 被樹化時,最小的hash表容量,默認爲 64 。
//當散列表容量小於該閾值,即使桶中bin的數量超過了 treeify_threshold ,也不會進行樹化,只會進行擴容操作。
static final int MIN_TREEIFY_CAPACITY = 64;
在HashMap裏面定義了一個常量TREEIFY_THRESHOLD
,默認爲8。當鏈表中的節點數量大於TREEIFY_THRESHOLD
時,鏈表將會考慮改爲紅黑樹,代碼是在上面putVal()方法的這一部分。
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)
//如果小於64進行擴容,不轉化 紅黑樹
resize();
//(n - 1) & 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);
}
}
TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
return new TreeNode<>(p.hash, p.key, p.value, next);
}
可以看到,如果table長度小於常量MIN_TREEIFY_CAPACITY
時,不會變爲紅黑樹,而是調用resize()方法進行擴容。MIN_TREEIFY_CAPACITY
的默認值是64。顯然HashMap認爲,雖然鏈表長度超過了8,但是table長度太短,只需要擴容然後重新散列一下就可以。
從代碼中可以看到,變爲紅黑樹的必要條件是鏈表的節點是大於8,且table(數組)長度已經大於64。下次執行 resize 判斷樹的節點個數低於 6,也再會把樹轉化爲鏈表。
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;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
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);
}
五、HashMap擴容機制
當HashMap決定擴容時,會調用HashMap類中的resize
方法,參數是新的table長度。在JDK1.7
和JDK1.8
的擴容機制有很大不同。
5.1、JDK1.7下的擴容機制
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
Entry[] newTable = new Entry[newCapacity];
transfer(newTable, initHashSeedAsNeeded(newCapacity));
table = newTable;
threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}
代碼中可以看到,如果原有table長度已經達到了上限,就不再擴容了。
如果還未達到上限,則創建一個新的table,並調用transfer方法進行擴容,並重新計算hash值,比較消耗時間
:
void transfer(Entry[] newTable) {
Entry[] src = table; //src引用了舊的Entry數組
int newCapacity = newTable.length;
for (int j = 0; j < src.length; j++) { //遍歷舊的Entry數組
Entry<K,V> e = src[j]; //取得舊Entry數組的每個元素
if (e != null) {
src[j] = null;//釋放舊Entry數組的對象引用(for循環後,舊的Entry數組不再引用任何對象)
do {
Entry<K,V> next = e.next;
int i = indexFor(e.hash, newCapacity); //!!重新計算每個元素在數組中的位置
e.next = newTable[i]; //標記[1]
newTable[i] = e; //將元素放在數組上
e = next; //訪問下一個Entry鏈上的元素
} while (e != null);
}
}
}
transfer方法的作用是把原table的Node放到新的table中,使用的是頭插法,也就是說,新table中鏈表的順序和舊列表中是相反的,在HashMap線程不安全的情況下,這種頭插法可能會導致環狀節點
。
static int indexFor(int h, int length) {
return h & (length-1);
}
5.2、JDK1.8上的擴容機制
JDK1.8對resize()方法進行很大的調整,JDK1.8的resize()方法如下:
final Node<K, V>[] resize() {
//得到當前數組
Node<K, V>[] oldTab = table;
//如果當前數組== null 返回 0,否則返回數組長度
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//當前閾值點,默認 12 (16 * 0.75)
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
// 如果capacity已經擴容到最大(2^31-1),則不進行擴容
threshold = Integer.MAX_VALUE;
return oldTab;
} else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)
// capacity > 16 且 capacity*2 < MAXIMUM_CAPACITY, 則進行擴容2倍
newThr = oldThr << 1;
} else if (oldThr > 0)
// 如果capacity < 0 且 threshold > 0, 則 capacity = threshold
newCap = oldThr;
else {
// 如果capacity < 0 且 threshold < 0, 初始化table(都使用默認值)
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int) (DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 計算新的threshold
if (newThr == 0) {
float ft = (float) newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float) MAXIMUM_CAPACITY ? (int) ft : Integer.MAX_VALUE);
}
threshold = newThr;
// 將舊table中的數據移到擴容後的table中
@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)
// 如果舊table的桶中只有一個bin, 將bin直接剪切到新table中
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
// 如果舊table的桶是樹形bin, 使用樹複製方式
((TreeNode<K, V>) e).split(this, newTab, j, oldCap);
else {
// 如果舊table的桶是線性鏈表bin, 使用鏈表複製方式
Node<K, V> loHead = null, loTail = null;
Node<K, V> hiHead = null, hiTail = null;
Node<K, V> next;
do {
next = e.next;
// 由於 存儲位置 = Key.hashCode ^ (capacity-1), capacity擴大2倍後,key的hash值也會向左多取1位
// 若多取的最高爲0, hash值保持不變; 若爲1, hash值則擴大2倍
// 下面的代碼就是將原來的鏈表, 根據擴大後的新hash值,拆分爲兩個鏈表,分別存儲在新table中的不同桶中。
// lo 代表高位爲0, hi 代表高位爲1, tail 爲鏈尾, head 爲鏈頭
if ((e.hash & oldCap) == 0) { //高位 == 0
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
} else { //高位 == 1
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
// 將 lo 鏈表放到新table的 j 位置, 將 hi鏈表放置到新鏈表的 j+oldCapacity 位置
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead; //原來索引位置 j
}
if (hiTail != null) {
hiTail.next = null;
//新的索引位置 = oldCap舊錶的長度 + 索引位置 j
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
從上面源碼可的擴容時,計算新的索引高位
是 0
保存到原來的索引位置;如果高位
是1
那麼存儲到原來索引 + 舊容量的數組長度的位置
如(舊值5 + 數組長度16 )
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;
// 樹形Bin的複製其實與線性鏈表bin很相似, 也是根據擴容後hash值的最高位, 分解成兩個鏈表
// 區別在於分解後的兩個鏈表, 如果 元素個數 < UNTREEIFY_THRESHOLD ,會將樹轉化爲線性鏈表bin; 否則就會進行樹化
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) {
//UNTREEIFY_THRESHOLD = 6
if (lc <= UNTREEIFY_THRESHOLD)
tab[index] = loHead.untreeify(map); // 轉化爲線性鏈表
else {
tab[index] = loHead;
if (hiHead != null)
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);
}
}
}
列表的位置取模運算: (n - 1) & hash
第一次擴容:16
0000 0000 0000 0000 0000 0000 0000 1111 : 容量 :n = 15
0000 0000 0000 0000 0000 0000 0001 0011 : hash值 :hash = 19
取模:
0000 0000 0000 0000 0000 0000 0000 0011 : 結果 :n = 3第二次擴容:32
0000 0000 0000 0000 0000 0000 0001 1111 : 容量 :n = 31
0000 0000 0000 0000 0000 0000 0001 0011 : hash值 :hash = 19
取模:
0000 0000 0000 0000 0000 0000 0001 0011 : 結果 :n = 19可得:
擴容後最高位是0 ,保持在原來的位置;
擴容後最高位是1 ,保持在原來的位置 + 擴容前的容量;
六、獲取元素 (get)
- get方法
public V get(Object key) {
Node<K,V> e;
//根據 hash 和 key 獲取 Node 結點,並返回節點的 value
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
transient Node<K,V>[] table;
final Node<K,V> getNode(int hash, Object key) {
//臨時變量儲存tab數組
Node<K,V>[] tab;
//first 臨時變量獲取第一個元素
//e 爲臨時變量儲存在first元素不是所需元素的下一個元素
Node<K,V> first, e;
//n爲table的長度
int n;
K k;
//如果tab已經被初始化切table數組的長度大於0,在已知元素的查找位置上有元素則進入if判斷
//否則返回null,即沒有找到元素
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
/**
* 以下兩個條件與
* 1、first.hash == hash: 頭節點的hash值與待查找key的hash值相同
* 2、((k = first.key) == key || (key != null && key.equals(k))):key值相等
* 當這兩個條件同時滿足,說明頭節點即是待查找的元素,直接返回頭節點
*/
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
// 否則在後繼節點中查找,e-當前遍歷的節點
if ((e = first.next) != null) {
if (first instanceof TreeNode)
//如果當前節點是紅黑樹節點,那麼直接在紅黑樹中查找元素
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//如果鏈表沒有被樹化,則使用鏈表的方式查詢.
do {
//循環判斷當前的臨時變量e是否與所需元素相同
//相同則返回e元素,不相同則返回null
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
執行 TreeNode#getTreeNode
/**
* Calls find for root node.
*/
final TreeNode<K,V> getTreeNode(int h, Object k) {
return ((parent != null) ? root() : this).find(h, k, null);
}
執行此 TreeNode#find
方法,獲取節點:
/**
* 這是TreeNode的內部方法
* 1、先比較hash值,看是在左子樹找還是右子樹找;
* 2、再判斷key是否相等,如果相等就直接返回;如果不相等,那麼就看那邊不爲空就在那邊找;
* 3、如果左右節點都不爲空的話,那麼就要通過Comparable方法來比較是在左子樹還是右子樹查找
*/
final HashMap.TreeNode<K, V> find(int h, Object k, Class<?> kc) {
HashMap.TreeNode<K, V> p = this;
do {
// ph-遍歷節點的hash值,dir-位置標誌位,小於0,左子樹查找,大於等於0,右子樹查找,pk-遍歷節點的key值
int ph, dir;
K pk;
HashMap.TreeNode<K, V> pl = p.left, pr = p.right, q;
// 大於遍歷節點大於查找key對應的hash值,在遍歷節點的左子樹查找
if ((ph = p.hash) > h)
p = pl;
// 大於遍歷節點小於查找key對應的hash值,在遍歷節點的左子樹查找
else if (ph < h)
p = pr;
// 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;
// 如果實現了Comparable接口並且也比較出了大小,那就可以明確是在左子樹還是右子樹查找,
//如果無法實現的話,那麼就在左子樹或者右子樹遞歸查找
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;
}
七、移除元素 (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,(n - 1) & hash 是節點對應的位置
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
//如果 hash 相等, key 相等
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p; //返回數組位置上的節點 node
else if ((e = p.next) != null) {
//p 的next 節點不爲空,這是遍歷鏈表上的節點 node
if (p instanceof TreeNode) //如果樹查詢節點,步驟在get方法中
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);
}
}
//刪除節點,matchValue 驗證是否匹配
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; //修改次數加1
--size; //節點個數減1
afterNodeRemoval(node);
return node;
}
}
return null;
}
- 在樹中移出節點
TreeNode#removeTreeNode
final void removeTreeNode(HashMap<K,V> map, Node<K,V>[] tab,
boolean movable) {
int n;
//tab 表 == null 或 length == 0 直接返回
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;
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;
}
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;
}
//balanceDeletion :左旋,右旋 使樹平衡
TreeNode<K,V> r = p.red ? root : (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;
}
}
//movable = true
if (movable)
moveRootToFront(tab, r);
}
八、初始化
當我們初始化HashMap並設置大小,大小不是 2 的冪會發生什麼呢?
//初始化大小爲 11
HashMap map = new HashMap<String, String>(11)
- 源碼做的事情如下:
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
//initialCapacity 初始化大小
//loadFactor :加載因子 == 0.75
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
//設置擴容閾值 threshold。就是決定是否擴容的邊界值
//tableSizeFor 位運算得到最接近 2 的冪
//在 put 方法中會重新對閾值 threshold 進行修改
this.threshold = tableSizeFor(initialCapacity);
}
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;
//MAXIMUM_CAPACITY最大容量 2^30
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
根據上面的算法可以得到,其會返回 cap
也就大於cap且最接近的2的冪,如:cap = 12,返回 :16
前提:當輸入 12
cap :12
n :cap - 1 = 11 : 主要是爲了防止輸入的值剛好是2的冪
n |= n >>> 1
0000 0000 0000 0000 0000 0000 0000 1011 : n = 11
0000 0000 0000 0000 0000 0000 0000 0101 : n >>> 1 = 5
------------------------------------------------------
0000 0000 0000 0000 0000 0000 0000 1111 : n = 15
n |= n >>> 2
0000 0000 0000 0000 0000 0000 0000 1111 : n = 15
0000 0000 0000 0000 0000 0000 0000 0011 : n >>> 2 = 3
------------------------------------------------------
0000 0000 0000 0000 0000 0000 0000 1111 : n = 15
n |= n >>> 4
0000 0000 0000 0000 0000 0000 0000 1111 : n = 15
0000 0000 0000 0000 0000 0000 0000 0000 : n >>> 4 = 0
------------------------------------------------------
0000 0000 0000 0000 0000 0000 0000 1111 : n = 15
當執行:return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1
可得返回:n + 1 = 16