Hashmap 源碼分析之基本操作
我們從流程中看一下,這個hashmap究竟是這么實現(xiàn)的毛好。
我們先了解一下put方法實現(xiàn)
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
接下來的才是真正實現(xiàn):
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
//數(shù)組tab table是內(nèi)部數(shù)組
Node<K,V>[] tab;
Node<K,V> p;
int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
// resize()是擴容函數(shù)
n = (tab = resize()).length;
//取到hash地址浇坐,如果為null就可以填入
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
//不為null
Node<K,V> e; K k;
//如果map中已經(jīng)存在科平,就將值覆蓋
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//如果這個結(jié)點是紅黑樹的結(jié)點桨螺,那么使用putTreeVal來實現(xiàn)科汗。
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//如果是鏈表結(jié)構(gòu)
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//假如這個鏈表結(jié)點個數(shù)大于等于TREEIFY_THRESHOLD - 1的時候的時候般卑,直接轉(zhuǎn)換成樹
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// key已經(jīng)存在直接覆蓋value
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;
//onlyIfAbsent if true, don't change existing value
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
//這個是一個安全機制 modCount在LinkedList講過
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
至于afterNodeInsertion這些武鲁,在hashmap中其實是沒有實現(xiàn)的爽雄,
// Callbacks to allow LinkedHashMap post-actions
void afterNodeAccess(Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { }
void afterNodeRemoval(Node<K,V> p) { }
正如上面寫的蝠检,應(yīng)該是和LinkedhashMap有關(guān)系。
我們接下來看挚瘟,get方法叹谁,注意hashmap是可以有null值的
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
同樣真正實現(xiàn)是在
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab;
Node<K,V> first, e;
int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//如果第一個存在,并可以key值相同返回first
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//沒有找到的話
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);
}
}
return null;
}
接下來就是hashmap擴容了
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) // 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) {
//為null利于gc回收處理
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);
//將舊的table對于到擴容的table上
//擴了一倍焰檩,那么其實是就是高位新增一位判斷是1 還是0
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
那么其實我們可以看到hashmap擴容其實非常的耗時間,如果可以預(yù)測這個map可以存的值數(shù)量订框,其實在初始化的時候定義是更加合算的析苫。
讀源碼,是我們了解大神領(lǐng)域的一大捷徑
生命不息穿扳,奮斗不止