java.utl.HashMap 原始碼解讀
阿新 • • 發佈:2019-01-02
目錄
4. JDK8以後, 如果相同HasHcode所在位置的Node連結串列長度超過指定閾值會自動轉換成TreeNode紅黑樹儲存
5. JDK8以後, 如果相同HasHcode所在位置的TreeNode紅黑樹長度低於指定閾值會自動轉換成Node連結串列儲存
1. HashMap容器預設的初始化大小為16
/**
* 預設的初始化大小
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
2. HashMap預設的負載因子為0.75
/**
* 容器擴容的負載因子
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
3. HashMap的儲存容器為陣列
/**
* HashMap為陣列結構, 每個hash儲存在指定的節點上, 如果遇到hash相同的節點
* 會以連結串列或者紅黑樹的形式儲存
*/
transient Node<K, V>[] table;
4. JDK8以後, 如果相同HasHcode所在位置的Node連結串列長度超過指定閾值會自動轉換成TreeNode紅黑樹儲存
/** * 轉換成Tree的閾值, 超過這個閾值為轉換成Tree結構 */ static final int TREEIFY_THRESHOLD = 8;
5. JDK8以後, 如果相同HasHcode所在位置的TreeNode紅黑樹長度低於指定閾值會自動轉換成Node連結串列儲存
/**
* 由Tree轉換回來的閾值,低於這個閾值將被轉換為HashTable
*/
static final int UNTREEIFY_THRESHOLD = 6;
6. 版本號,併發情況下用於快速迭代失敗
/**
* 版本號,記錄當前容器的操作次數,多執行緒情況下快速失敗迭代
*/
transient int modCount;
7. 新增元素方法解讀
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)
n = (tab = resize()).length;
//根據hash分配儲存位置, 如果該位置為空的話,放置一個新的節點
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//根據hash分配儲存位置, 如果該位置已存在節點
else {
Node<K, V> e;
K k;
//如果當前節點和將要放入的key相同, 保留最新的節點資訊
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//如果是TreeNode的話,呼叫TreeNode的方法
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);
//新增元素之後,判定是否需要轉成TreeNode
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//如果找到key相同的節點,保留當前節點的資訊為新加入的節點,跳出迴圈
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//如果有相同hash和key的節點的話,返回被覆蓋掉的value
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
//替換節點,節點數不發生變化,不需要檢查版本號和擴容,直接return就可以
return oldValue;
}
}
//版本號++
++modCount;
//節點數量++ 如果大於閾值的話,需要進行擴容
if (++size > threshold)
resize();
//插入後的回掉函式,目前未做實現處理
afterNodeInsertion(evict);
//新增節點,不返回任何資訊
return null;
}
8. 容器的擴容機制
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
}
//如果原來的閾值>0, 賦值為新的閾值
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
//如果原來的閾值為0的話,新的容器走預設閾值
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;//將原來的節點位置置空, 便於GC回收
//如果沒有連結串列節點, 根據hash重新分配位置
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
//如果是TreeNode, 操作TreeNode
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;
}
9. hashcode的計算方式
/**
* 右位移16位,正好是32bit的一半,自己的高半區和低半區做異或,就是為了混合原始雜湊碼的高位和低位,
* 以此來加大低位的隨機性。而且混合後的低位摻雜了高位的部分特徵,這樣高位的資訊也被變相保留下來。
* <p>
* 這段程式碼是為了對key的hashCode進行擾動計算,防止不同hashCode的高位不同但低位相同導致的hash衝突。
* 簡單點說,就是為了把高位的特徵和低位的特徵組合起來,降低雜湊衝突的概率,也就是說,儘量做到任何一位的變化都能對最終得到的結果產生影響。
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
10. Node連結串列結構 - 單鏈表
/**
* 陣列的節點實體,容器中的每個元素都是會儲存為一個Node
*/
static class Node<K, V> implements Map.Entry<K, V> {
final int hash; //當前節點的hash值
final K key;
V value;
Node<K, V> next; //下一個節點的地址, 相同hash的節點會儲存為一個連結串列
Node(int hash, K key, V value, Node<K, V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
11. TreeNode紅黑樹結構
/**
* 紅黑樹實現的節點, 當連結串列的長度超過閾值的時候,會將連結串列格式轉換為紅黑色
*/
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;
TreeNode(int hash, K key, V val, Node<K, V> next) {
super(hash, key, val, next);
}