HashMap是數(shù)組+鏈表+紅黑樹错维。
上圖就是一個(gè)Node數(shù)組
transient Node<K,V>[] table;
每個(gè)黑點(diǎn)就是個(gè)Node
static class Node<K,V> implements Map.Entry<K,V> {
final int hash; //這個(gè)hash是key的hash
final K key;
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;
}
}
Node.hash是key的hash
1.8的HashMap增加了紅黑樹來增加存取效率纳猪,紅黑樹的節(jié)點(diǎn)
TreeNode
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V>
//下面是LinkedHashMap.Entry
static class Entry<K,V> extends HashMap.Node<K,V>
這樣是為了紅黑樹與鏈表之間的轉(zhuǎn)換赞枕。TreeNode的方法很多惭聂,就不貼出來了弥奸。
關(guān)于hash蛤克,數(shù)組容量
HashMap有四個(gè)構(gòu)造器泽论,我們以其中兩個(gè)來說說其過程
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
數(shù)組大小16漓库,閥值12
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
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;
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;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
并不會(huì)初始化數(shù)組大小亦鳞,反而會(huì)先設(shè)置閥值threshold晨抡,tableSizeFor會(huì)返回大于等于傳入值的最小2的指數(shù)。如傳入17见剩,返回32(2^5)期揪。那么什么時(shí)候初始化數(shù)組大刑拼 悟衩?第一次調(diào)用put時(shí)剧罩,在putVal中在這種情況下會(huì)調(diào)用resize方法,在該方法中會(huì)在閥值不為零而數(shù)組未初始化的情況下將數(shù)組大小設(shè)為閥值大小座泳。
所以不管怎樣數(shù)組大小一定是2的指數(shù)惠昔,為什么?HashMap的Hash算法本質(zhì)上是三步:取key的hashCode值挑势、高位運(yùn)算镇防、取模運(yùn)算。
- key的hash計(jì)算
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
高16位異或低16位薛耻。這樣保證在數(shù)組較小的情況下营罢,hashcode的高位也能被考慮進(jìn)來,減少?zèng)_突饼齿。
- key在table[]中位置計(jì)算
(n - 1) & hash
這里便是上面問題的解答饲漾,讓大小是2^n,是為了對(duì)取模運(yùn)算進(jìn)行優(yōu)化缕溉,&比%具有更高的效率考传,當(dāng)length總是2的n次方時(shí),h& (length-1)運(yùn)算等價(jià)于對(duì)length取模证鸥,也就是h%length僚楞。
一般情況下我們考慮素?cái)?shù)作為數(shù)組的大小,素?cái)?shù)導(dǎo)致沖突的概率小于合數(shù)枉层,例如HashTable初始就是11泉褐。為什么一般hashtable的桶數(shù)會(huì)取一個(gè)素?cái)?shù)
之前文章中介紹過散列表,對(duì)于一個(gè)散列表來說存取效率和兩方面有關(guān):1.hash函數(shù):計(jì)算結(jié)果分散越均勻鸟蜡,hash碰撞的概率就越小膜赃,存取效率就會(huì)越高; 2揉忘,擴(kuò)容機(jī)制跳座,數(shù)組太大浪費(fèi)空間,太小費(fèi)時(shí)間泣矛。
擴(kuò)容機(jī)制resize
超過閥值進(jìn)行擴(kuò)容疲眷,閥值threshold = capacity * loadFactor,來看看擴(kuò)容過程
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;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // 有一個(gè)構(gòu)造函數(shù)是接收map的您朽,這種情況threshold會(huì)被賦值狂丝,而數(shù)組并沒初始化
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
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;
}
resize不僅承擔(dān)了擴(kuò)容的功能,還有初始化數(shù)組大小的功能哗总。
1.如果oldCap > 0几颜,將數(shù)組大小擴(kuò)大兩倍,閥值同樣擴(kuò)大兩倍
2.如果oldCap == 0 && oldThr > 0魂奥,比如調(diào)用了規(guī)定容量大小的構(gòu)造函數(shù)菠剩。將容量設(shè)為閥值大小。
3.如果oldCap ==0代表初始化操作耻煤,數(shù)組大小為16具壮,閥值為12。
3.接下來如果oldTab != null代表是擴(kuò)容操作哈蝇,對(duì)節(jié)點(diǎn)重新定位棺妓,一個(gè)節(jié)點(diǎn)的hash是key的hash,在確定它在數(shù)組中的位置是在putVal方法中炮赦,采用的是hash & (capacity-1)怜跑,capacity能取什么值?2的指數(shù)倍,那么在重新安排新位置時(shí)先遍歷數(shù)組性芬,針對(duì)每個(gè)bin峡眶,將里面的節(jié)點(diǎn)按照hash & capacity分為兩撥,一波hash & capacit == 0放在舊位置處植锉,另一波放在oldCap + 舊位置 = 新位置處辫樱。
這張圖顯示了擴(kuò)容后節(jié)點(diǎn)的重新安排。
擴(kuò)容后數(shù)組變?yōu)樵瓉淼膬杀犊”樱敲匆粋€(gè)節(jié)點(diǎn)的hash & (capacity-1)的值要么等于原來狮暑,要么移動(dòng)2的冪次方。
這個(gè)設(shè)計(jì)確實(shí)非常的巧妙辉饱,既省去了重新計(jì)算hash值的時(shí)間搬男,而且同時(shí),由于新增的1bit是0還是1可以認(rèn)為是隨機(jī)的彭沼,因此resize的過程缔逛,均勻的把之前的沖突的節(jié)點(diǎn)分散到新的bucket了
4.再來說說TreeNode的split方法,同鏈表處理相同溜腐,仍分為兩撥译株,分法也一樣,這里當(dāng)其中一方節(jié)點(diǎn)數(shù)<=6挺益,則恢復(fù)成鏈表歉糜;否則重新樹化treeify。
2.HashMap的put方法
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;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
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))))
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);
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;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
putVal的邏輯很清晰望众,如果key存在onlyIfAbsent為false表示更新value值匪补,至于afterNodeAccess與afterNodeInsertion與LinkedHashMap有關(guān)。其他的比如要考慮到普通節(jié)點(diǎn)還是樹節(jié)點(diǎn)烂翰,普通節(jié)點(diǎn)插入后還要判斷是否進(jìn)行樹化夯缺。如果數(shù)量大于閥值就得進(jìn)行resize。注意threshold指的是節(jié)點(diǎn)總數(shù)而不是數(shù)組大小甘耿。
圖里鏈表長(zhǎng)度是否大于8判斷這塊踊兜,這里源碼的邏輯是如果key原先鏈表有則替換value值,否則將鍵值對(duì)插入鏈表佳恬,之后如果長(zhǎng)度大于8捏境,將鏈表樹化。
樹化調(diào)用的是treeifyBin
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)
resize();
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);
}
}
當(dāng)數(shù)組大小 < 64時(shí)毁葱,執(zhí)行擴(kuò)容操作垫言。即當(dāng)某個(gè)bin的節(jié)點(diǎn)個(gè)數(shù)大于8,但數(shù)組大小 < 64倾剿,進(jìn)行擴(kuò)容而不是樹化筷频。
關(guān)于HashMap的死循環(huán)
1.7的HashMap在多線程下resize是會(huì)出現(xiàn)死循環(huán),導(dǎo)致cpu100%,原因是1.7的resize會(huì)將原先節(jié)點(diǎn)的順序倒過來凛捏。死循環(huán)問題的定位一般都是通過jps+jstack查看堆棧信息來定位的
1.8擴(kuò)容時(shí)保持了原來鏈表中的順序担忧,避免了這個(gè)問題。
HashMap的table為什么是transient的
transient Entry[] table;也就是說table里面的內(nèi)容不會(huì)被序列化葵袭,為什么涵妥?
對(duì)HashMap來說hashcode至關(guān)重要乖菱,而Object里hashcode是native方法public native int hashCode();坡锡。這意味著的是:HashCode和底層實(shí)現(xiàn)相關(guān),不同的虛擬機(jī)可能有不同的HashCode算法窒所。
Java的優(yōu)勢(shì)跨平臺(tái)性鹉勒,如果不用transient修飾table,那么便會(huì)失去這一特性吵取。
來看看java重寫的writeObject與readObject
private void writeObject(java.io.ObjectOutputStream s)
throws IOException {
int buckets = capacity();
// Write out the threshold, loadfactor, and any hidden stuff
s.defaultWriteObject();
s.writeInt(buckets);
s.writeInt(size);
internalWriteEntries(s);
}
void internalWriteEntries(java.io.ObjectOutputStream s) throws IOException {
Node<K,V>[] tab;
if (size > 0 && (tab = table) != null) {
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
s.writeObject(e.key);
s.writeObject(e.value);
}
}
}
}
在writeObject選擇將key和value追加到序列化的文件最后面
private void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException {
// Read in the threshold (ignored), loadfactor, and any hidden stuff
s.defaultReadObject();
reinitialize();
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new InvalidObjectException("Illegal load factor: " +
loadFactor);
s.readInt(); // Read and ignore number of buckets
int mappings = s.readInt(); // Read number of mappings (size)
if (mappings < 0)
throw new InvalidObjectException("Illegal mappings count: " +
mappings);
else if (mappings > 0) { // (if zero, use defaults)
// Size the table using given load factor only if within
// range of 0.25...4.0
float lf = Math.min(Math.max(0.25f, loadFactor), 4.0f);
float fc = (float)mappings / lf + 1.0f;
int cap = ((fc < DEFAULT_INITIAL_CAPACITY) ?
DEFAULT_INITIAL_CAPACITY :
(fc >= MAXIMUM_CAPACITY) ?
MAXIMUM_CAPACITY :
tableSizeFor((int)fc));
float ft = (float)cap * lf;
threshold = ((cap < MAXIMUM_CAPACITY && ft < MAXIMUM_CAPACITY) ?
(int)ft : Integer.MAX_VALUE);
// Check Map.Entry[].class since it's the nearest public type to
// what we're actually creating.
SharedSecrets.getJavaOISAccess().checkArray(s, Map.Entry[].class, cap);
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] tab = (Node<K,V>[])new Node[cap];
table = tab;
// Read the keys and values, and put the mappings in the HashMap
for (int i = 0; i < mappings; i++) {
@SuppressWarnings("unchecked")
K key = (K) s.readObject();
@SuppressWarnings("unchecked")
V value = (V) s.readObject();
putVal(hash(key), key, value, false, false);
}
}
}
在readObject的時(shí)候重構(gòu)HashMap數(shù)據(jù)結(jié)構(gòu)禽额。
參考
推薦篇文章,圖片豐富條例清晰,Java8系列之重新認(rèn)識(shí)HashMap