本文基于jdk1.8進行解讀
其實HashMap最主要的幾個方法分別是
- put(設(shè)置值)
- get(獲取值)
- initTable(初始化hash表)
- resize(擴容)
- treeifyBin(樹化)
- untreeify(退化為鏈表)
- put方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
// 高16位與低16位做異或络拌,防止map容量較小時,hash沖突概率較大
// 假設(shè)我map容量為16,取模后都會剩下低四位,那只要我低四位相同就一定會沖突
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;
// 如果hash表未初始化
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// (n - 1) & hash 是對hash取模tab.length(map的容量),這也是HashMap大小一定是2的冪的原因
// 如果hash取模后,通過索引在hash表中獲取數(shù)據(jù)為空
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
// 如果hash取模后,通過索引在hash表中獲取數(shù)據(jù)不為空
else {
Node<K,V> e; K k;
// p是第一步的if里面獲取到的node,這里判斷hash與key是否相同,因為key可為null,所以key對比有兩步
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 其實第一步判斷了是否相同,后面就是樹和鏈表的處理邏輯了
// 獲取的node為樹
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
// 獲取到node為普通node
else {
// 遍歷node鏈表,binCount為鏈表長度-1
for (int binCount = 0; ; ++binCount) {
// 鏈表末尾
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
// 大于等于轉(zhuǎn)樹的長度
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是否相同的邏輯中敢订,e = p | 在node鏈表遍歷過程中, e = p.next
// 即e是與要設(shè)置的值key相同的節(jié)點
if (e != null) { // existing mapping for key
V oldValue = e.value;
// 這里替換node的value,onlyIfAbsent這個字段是是否值不存在時才設(shè)置
if (!onlyIfAbsent || oldValue == null)
e.value = value;
// 值替換后續(xù)處理,主要是LinkedHashMap使用
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
// 如果node增加后大小大于閾值,擴容
if (++size > threshold)
resize();
// node 插入后處理,主要是LinkedHashMap使用
afterNodeInsertion(evict);
return null;
}
- 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;
// table 已初始化
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// 檢查頭節(jié)點是否為對應(yīng)的數(shù)據(jù)
if (first.hash == hash &&
((k = first.key) == key || (key != null && key.equals(k))))
return first;
// 非頭節(jié)點數(shù)據(jù)情況
if ((e = first.next) != null) {
// 是否為紅黑樹
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
// 遍歷鏈表
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
// table 為空返回null
return null;
}
- initTable
- resize
hashMap中initTable使用的直接是resize方法,所以一起看
final Node<K,V>[] resize() {
// 拿到整個hash表
Node<K,V>[] oldTab = table;
// hash表如果未初始化,oldCap=0
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
// hash表已初始化
if (oldCap > 0) {
// 已經(jīng)是最大容量了
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 擴容也沒有達到最大容量的情況下,capacity和threshold都左移一位缆八,相當于乘2
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
// 未初始化,使用了帶參構(gòu)造胞谭,oldThr = threshold = tableSizeFor(initialCapacity)
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
// 未初始化,使用了無參構(gòu)造
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY; // 16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 16 * 0.75 = 12
}
// 帶參構(gòu)造未初始化
// 擴容后會超過 MAXIMUM_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;
// 將node塞入新表
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
// 單一的node節(jié)點
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
// 樹節(jié)點
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
// 鏈表節(jié)點
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;
}
- treeifyBin
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
// 如果hash表未初始化或表大小小于轉(zhuǎn)換樹的最小大小
// 這里明顯tab == null的判斷只是防止空指針,真正目的在于判斷map的capacity是否大于64
// 擴容
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);
}
}
- untreeify
final Node<K,V> untreeify(HashMap<K,V> map) {
Node<K,V> hd = null, tl = null;
for (Node<K,V> q = this; q != null; q = q.next) {
Node<K,V> p = map.replacementNode(q, null);
if (tl == null)
hd = p;
else
tl.next = p;
tl = p;
}
return hd;
}