HashMap源碼解讀
參考文章:https://mp.weixin.qq.com/s/YdUQTuG524SYNHwS22mg1Q
常量解析:
// 默認(rèn)初始化數(shù)組長(zhǎng)度
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// 最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
// 默認(rèn)裝載因子,默認(rèn)值為0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 樹(shù)化的列表深度閾值
static final int TREEIFY_THRESHOLD = 8;
// 反樹(shù)化(鏈表化)的深度閾值
static final int UNTREEIFY_THRESHOLD = 6;
// 最小的可樹(shù)化的數(shù)組長(zhǎng)度
static final int MIN_TREEIFY_CAPACITY = 64;</pre>
屬性解析:
// 大名鼎鼎的Node數(shù)組
transient Node<K,V>[] table;
// 緩存的鍵值對(duì)們
transient Set<Map.Entry<K,V>> entrySet;
// 數(shù)組大小
transient int size;
// 記錄當(dāng)前集合被修改的次數(shù)
transient int modCount;
// 擴(kuò)容的臨界值
int threshold;
// 裝載因子
final float loadFactor;
構(gòu)造方法解析:
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;
// 將臨界值初始化為數(shù)組大小,tableSizeFor: 將初始化值設(shè)置為是2的整數(shù)次冪(eg. 10 -> 16)
this.threshold = tableSizeFor(initialCapacity);
}
tableSizeFor原理:
static final int tableSizeFor(int cap) {
// 此處-1史飞,對(duì)應(yīng)了最后的 +1
// 如果不減1 尖昏,如果cap為2的N次方的話,則計(jì)算值為2的N次方的階乘祸憋,與預(yù)期不符
// 本質(zhì)是如果cap值為2的N次方時(shí)会宪,使得其對(duì)應(yīng)的二進(jìn)制數(shù)位數(shù)-1
int n = cap - 1;
/** 本質(zhì)邏輯就是通過(guò)位移使得每個(gè)二進(jìn)制位都為1 */
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
// n+1 ,對(duì)應(yīng)之前的-1操作
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
hash方法和計(jì)算數(shù)組下標(biāo)解析:
static final int hash(Object key) {
int h;
/**
* 低16位是和高16位進(jìn)行異或肖卧,高16位保持不變蚯窥。
* 一般的數(shù)組長(zhǎng)度都會(huì)比較短,取模運(yùn)算中只有低位參與散列塞帐;
* 高位與低位進(jìn)行異或拦赠,讓高位也得以參與散列運(yùn)算,使得散列更加均勻
* 個(gè)人理解:也是重寫(xiě)hashCode方法導(dǎo)致不合理的hash算法問(wèn)題的兜底方案
*/
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
/**
* n = 數(shù)組size
* hash = hash方法計(jì)算結(jié)果
* 因?yàn)閿?shù)組下標(biāo)從0開(kāi)始葵姥,所以n-1即最大值荷鼠,hash值與n-1做&運(yùn)算,運(yùn)算值肯定會(huì)在0~(n-1)之間
* 結(jié)果等同于 hash % n,但是計(jì)算效率更高
*/
(n - 1) & hash
resize方法解析:
final Node<K,V>[] resize() {
// oldTab為原數(shù)組
Node<K,V>[] oldTab = table;
// 舊數(shù)組大小
int oldCap = (oldTab == null) ? 0 : oldTab.length;
// 舊數(shù)組臨界值(構(gòu)造方法會(huì)賦值為數(shù)組大欣菩摇)
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
// 健壯性考慮允乐,達(dá)到最大值時(shí)矮嫉,直接返回舊數(shù)組
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
// 數(shù)組擴(kuò)容,新數(shù)組擴(kuò)容為舊數(shù)組一倍(即左移1位)牍疏,保證數(shù)組大小為2的n次方
newThr = oldThr << 1; // double threshold
}
// 數(shù)組初始化部分(之前為空)
else if (oldThr > 0) // initial capacity was placed in threshold
// 因?yàn)閚ew HashMap時(shí)會(huì)賦值為數(shù)組大小蠢笋,所以新數(shù)組大小為舊臨界值
newCap = oldThr;
else {
// 健壯性考慮
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
// 初始化新臨界值,臨界值 = 數(shù)組長(zhǎng)度 * 裝載因子
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
// 將新臨界值賦予臨界值threshold
threshold = newThr;
// 將新數(shù)組賦予數(shù)組table
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
// 原數(shù)組中有值時(shí)鳞陨,數(shù)據(jù)rehash
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
// 將舊節(jié)點(diǎn)指向空
oldTab[j] = null;
if (e.next == null)// 僅有一個(gè)節(jié)點(diǎn)
// 重新計(jì)算下標(biāo)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
// 樹(shù)節(jié)點(diǎn)擴(kuò)容
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // 多節(jié)點(diǎn)鏈表擴(kuò)容
/**
* 數(shù)組的長(zhǎng)度始終是2的整數(shù)次冪昨寞,每次擴(kuò)展數(shù)組都是原來(lái)的2倍
* key在新的數(shù)組的hash結(jié)果只有兩種:
* 1. 在原來(lái)的位置
* 2. 在原來(lái)位置+原數(shù)組長(zhǎng)度。
*/
// lo鏈表 對(duì)應(yīng) 在原來(lái)的位置情況
Node<K,V> loHead = null, loTail = null;
// hi鏈表 對(duì)應(yīng) 在原來(lái)位置+原數(shù)組長(zhǎng)度情況
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do { // 循環(huán)直到鏈表尾部
next = e.next;
if ((e.hash & oldCap) == 0) {// 在原來(lái)的位置
// 當(dāng)前頭尾節(jié)點(diǎn)初始化
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {// 在原來(lái)位置 + 原數(shù)組長(zhǎng)度
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;
}
put方法解析:
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
// onlyIfAbsent = true厦滤,則不覆蓋存在的值
// evict = false援岩,則處于初始化中
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
// 數(shù)組為空,初始化數(shù)組
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)// 獲取對(duì)應(yīng)數(shù)組下標(biāo)對(duì)應(yīng)的節(jié)點(diǎn)為空
// 初始化新節(jié)點(diǎn)
tab[i] = newNode(hash, key, value, null);
else {
// 鏈表 or 樹(shù) 追加節(jié)點(diǎn)
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
// key相等掏导,則新值覆蓋舊值享怀,返回值為舊值
e = p;
else if (p instanceof TreeNode)
// 樹(shù)節(jié)點(diǎn)調(diào)用putTreeVal
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {// binCount 鏈表深度
if ((e = p.next) == null) {
// 尾插法
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // 深度達(dá)到閾值
//轉(zhuǎn)換為紅黑樹(shù)存儲(chǔ)(雙向鏈表)
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
// 當(dāng)前節(jié)點(diǎn)指向下一個(gè)節(jié)點(diǎn),即循環(huán)鏈表
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
// 覆蓋舊值
e.value = value;
// 回調(diào)
afterNodeAccess(e);
return oldValue;
}
}
// 將記錄修改次數(shù)加1碘菜,判斷是否需要擴(kuò)容凹蜈,如果需要就擴(kuò)容
++modCount;
if (++size > threshold)// 達(dá)到臨界值觸發(fā)擴(kuò)容
resize();
afterNodeInsertion(evict);
return null;
}