PUT方法背后的原理
如何存儲(chǔ)

image
1. 計(jì)算出key的hash值
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
擾動(dòng)處理混合哈希碼的高位和低位(實(shí)際上只擾動(dòng)了低位)。經(jīng)過(guò)擾動(dòng)處理,使得存儲(chǔ)Node的數(shù)組長(zhǎng)度在很小的時(shí)候(即取的低位很少時(shí))減少?zèng)_突。
2. 計(jì)算出存儲(chǔ)位置 i
i = (n - 1) & hash
其中n為數(shù)組長(zhǎng)度缺省為16見HashMap類的常量定義
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
一般我們常見的固定范圍均勻分散用%(模運(yùn)算),這邊使用&(與運(yùn)算)是因?yàn)榕c運(yùn)算具有更好的性能。
通過(guò)測(cè)試發(fā)現(xiàn)&操作在對(duì)0~100的數(shù)據(jù)分散到15個(gè)位置時(shí)并不能很好的均勻分布,但是在分散到16個(gè)位置時(shí)就沒(méi)有問(wèn)題。這是因?yàn)?6的二進(jìn)制數(shù)據(jù)為10000
低位全是0,減1后為1111,這時(shí)&運(yùn)算等價(jià)于%模運(yùn)算。這就是很多面試題中提到的為什么HashMap的數(shù)組長(zhǎng)度必須是2的n次冪的原因。
3. 創(chuàng)建Node對(duì)象并存儲(chǔ)到數(shù)組中
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
...
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
...
}
Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {
return new Node<>(hash, key, value, next);
}
不同的key計(jì)算出相同的存儲(chǔ)位置怎么辦

image
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;
// 1. 初始化table數(shù)組
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 2. 根據(jù)key的hash值計(jì)算出Node存放在數(shù)組中的位置,如果為null則直接存儲(chǔ)
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
// 3. 即將放入的key與之前存儲(chǔ)的key一致
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 4. 之前存儲(chǔ)的Node已經(jīng)升級(jí)為紅黑數(shù)結(jié)構(gòu)
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
// 5. 遍歷鏈表不存在則新增,長(zhǎng)度>=8時(shí)鏈表轉(zhuǎn)換成紅黑樹
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
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;
}
}
// 6. 存在則替換就的value
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
// 7. 長(zhǎng)度大于閥值進(jìn)行擴(kuò)容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
總結(jié):
- key的引用地址相等或者key的hash值相等并且equals方法返回true則認(rèn)為是相同的key,在設(shè)置了onlyIfAbsent=false 或者 舊的值為null時(shí)將進(jìn)行替換
- 當(dāng)鏈表長(zhǎng)度>=8時(shí)為了提高查詢效率會(huì)將鏈表結(jié)構(gòu)轉(zhuǎn)化為紅黑樹(紅黑樹細(xì)節(jié)會(huì)在TreeMap的源碼解讀中詳細(xì)描述)
- modCount用于記錄HashMap的修改次數(shù),HashMap不是線程安全的在讀取時(shí)修改數(shù)據(jù)迭代器就會(huì)拋出ConcurrentModificationException異常
- 存儲(chǔ)的鍵值對(duì)的個(gè)數(shù)>閥值(容量*負(fù)載因子)時(shí)會(huì)進(jìn)行數(shù)組擴(kuò)容
- 負(fù)載因子缺省為0.75這是一個(gè)權(quán)衡值。太大會(huì)加劇hash沖突,太小會(huì)造成空間浪費(fèi)
如何擴(kuò)容
/**
* resize方法會(huì)在第一次初始化或者容量不夠時(shí)被調(diào)用
*/
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;
}
// 沒(méi)有超過(guò)最大值則擴(kuò)容為原來(lái)數(shù)組長(zhǎng)度的2倍
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;
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
// 將舊的鏈表拆分成兩個(gè)鏈表
// 拆分規(guī)則:將hash與擴(kuò)容后新增的參與運(yùn)算的位進(jìn)行&運(yùn)算如果為0則存儲(chǔ)的原始位置,為1則存儲(chǔ)在原始位置+擴(kuò)容前的容量
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;
}
總結(jié):
- 擴(kuò)容為原來(lái)數(shù)組長(zhǎng)度的2倍
- 遍歷舊的數(shù)據(jù)將其移動(dòng)到新的數(shù)組中,遇到鏈表時(shí)將舊的鏈表拆分成兩個(gè)鏈表 拆分規(guī)則:將hash與擴(kuò)容后新增的參與運(yùn)算的位進(jìn)行&運(yùn)算如果為0則存儲(chǔ)的原始位置,為1則存儲(chǔ)在原始位置+擴(kuò)容前的容量(原因是使用的2次冪的擴(kuò)展即高位增加一位比如16擴(kuò)容到32 二進(jìn)制參與&運(yùn)算的n-1 由1111變成11111, 即hash需要與新增的高位10000進(jìn)行&運(yùn)算 ,運(yùn)算結(jié)果為0即數(shù)組下標(biāo)為原始位置;運(yùn)算結(jié)果為1則數(shù)組下標(biāo)為原始位置+擴(kuò)容前舊的容量)
GET方法為何能快速獲取值
public V get(Object key) {
Node<K,V> e;
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;
// 計(jì)算存放在數(shù)組table中的位置
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// 依次在數(shù)組、紅黑樹、鏈表中查找(通過(guò)equals()判斷)
// 1. 數(shù)組查找
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
// 2. 紅黑樹查找
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
// 3. 鏈表查找
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
HashMap在日常使用中會(huì)有哪些問(wèn)題?
線程不安全
JDK1.7 并發(fā)操作時(shí)resize方法易出行鏈表遍歷死循環(huán),JDK 1.8 轉(zhuǎn)移數(shù)據(jù)操作 = 按舊鏈表的正序遍歷鏈表、在新鏈表的尾部依次插入,所以不會(huì)出現(xiàn)鏈表 逆序、倒置的情況,故不容易出現(xiàn)環(huán)形鏈表的情況。
key為Object類型需要注意哪些問(wèn)題
- hashCode() 用于計(jì)算存儲(chǔ)位置,選擇不恰當(dāng)易造成hash碰撞影響性能
- equals() 保證key在哈希表中的唯一性
- hashCode()、equals() (如果進(jìn)行重寫操作,一定要確保同時(shí)被正確重寫)