1、putVal() 底層:Node數組+鏈表+紅黑樹 發生hash衝突的時候,在該下標尾部添加新結點成爲鏈表,鏈表的長度超過8則轉換爲紅黑樹
1)判斷key和value爲null則拋出空指針異常
2)通過二次hash計算出key對應的node節點數組下標
3)如果數組未被初始化,調用初始化的函數
4)如果對應下標的節點爲null,表示該下標的沒有節點,直接添加(這裏使用了cas無鎖機制,樂觀鎖的一種體現,大致思路是通過當前該位置的值V,現在爲null,和執行添加新結點時候該下標的值進行比較C,如果V==C,表示還沒有線程對該下標進行過更新操作,該下標對應的值仍爲null,則可以把新節點添加到這個位置)
5)如果當前hashmap正在擴容,則幫助擴容
6)發生了hash衝突
7)需要在添加前加鎖,以防形成閉環
8)雙重檢測,確定當前的節點是對應下標的節點
9)如果該key已存在,則覆蓋value值
10)遍歷完鏈表未找到key,則添加新結點到鏈表末尾
11)如果是樹節點類型,執行紅黑樹添加
12)如果鏈表長度大於8,則轉換爲紅黑樹
final V putVal(K key, V value, boolean onlyIfAbsent) {
1 if (key == null || value == null) throw new NullPointerException();
2 int hash = spread(key.hashCode());
int binCount = 0;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
3 if (tab == null || (n = tab.length) == 0)
tab = initTable();
4 else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
break; // no lock when adding to empty bin
}
5 else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
6 else {
V oldVal = null;
7 synchronized (f) {
8 if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node<K,V> e = f;; ++binCount) {
K ek;
9 if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
oldVal = e.val;
if (!onlyIfAbsent)
e.val = value;
break;
}
Node<K,V> pred = e;
10 if ((e = e.next) == null) {
pred.next = new Node<K,V>(hash, key,
value, null);
break;
}
}
}
11 else if (f instanceof TreeBin) {
Node<K,V> p;
binCount = 2;
if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
value)) != null) {
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
}
}
12 if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
2、get()方法
1)同樣是計算出當前key在數組的下標
2)如果是空數組則返回null,必須是已經有值的Node數組,並且對應下標的值不能爲null
3)下標存的值的key就是當前對應的key,直接返回value
4)樹,查找
5)鏈表查找
public V get(Object key) {
Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
1 int h = spread(key.hashCode());
2 if ((tab = table) != null && (n = tab.length) > 0 &&
(e = tabAt(tab, (n - 1) & h)) != null) {
3 if ((eh = e.hash) == h) {
if ((ek = e.key) == key || (ek != null && key.equals(ek)))
return e.val;
}
4 else if (eh < 0)
return (p = e.find(h, key)) != null ? p.val : null;
5 while ((e = e.next) != null) {
if (e.hash == h &&
((ek = e.key) == key || (ek != null && key.equals(ek))))
return e.val;
}
}
return null;
}
優秀理解:http://blog.csdn.net/u010887744/article/details/50637030