走一次HashMap的存取

忘了太多東西,好好複習。node

 

存:數組

 1 if ((tab = table) == null || (n = tab.length) == 0)
 2             n = (tab = resize()).length;//檢查容器大小
 3         if ((p = tab[i = (n - 1) & hash]) == null)
 4             tab[i] = newNode(hash, key, value, null); //無衝突
 5         else {
 6             Node<K,V> e; K k;
 7             if (p.hash == hash &&
 8                 ((k = p.key) == key || (key != null && key.equals(k))))//每次都判斷桶頭
 9                 e = p;                                                     
10             else if (p instanceof TreeNode)
11                 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); //若是當前的桶轉化成紅黑樹,調用紅黑樹的插入方法
12             else {
13                 for (int binCount = 0; ; ++binCount) { //遍歷桶
14                     if ((e = p.next) == null) {
15                         p.next = newNode(hash, key, value, null);//桶末尾插入
16                         if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
17                             treeifyBin(tab, hash);//桶的大小大於閾值(8)將該桶轉化爲紅黑樹
18                         break;
19                     }
20                     if (e.hash == hash &&
21                         ((k = e.key) == key || (key != null && key.equals(k))))      
22                         break;//找到桶中存在的Node
23                     p = e;
24                 }
25             }
26         ...
27 }

 

取:this

 

 1 final Node<K,V> getNode(int hash, Object key) {
 2         Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
 3         if ((tab = table) != null && (n = tab.length) > 0 &&
 4             (first = tab[(n - 1) & hash]) != null) {
 5             if (first.hash == hash && // always check first node
 6                 ((k = first.key) == key || (key != null && key.equals(k))))
 7                 return first;
 8             if ((e = first.next) != null) {
 9                 if (first instanceof TreeNode)
10                     return ((TreeNode<K,V>)first).getTreeNode(hash, key);      //找樹
11                 do {
12                     if (e.hash == hash &&
13                         ((k = e.key) == key || (key != null && key.equals(k))))  //找桶
14                         return e;
15                 } while ((e = e.next) != null);
16             }
17         }
18         return null;
19     }

 

 

Java 8的HashMap的存儲從 數組+鏈表(桶)變成了 數組+(鏈表/紅黑樹)。spa

1 if (p instanceof TreeNode)
2     ...

因此它的基本操做中都會出現這樣的代碼片斷。code

 

由於這樣的改動使得在Hash值相同的容器比較大的時候,它的查找效率不會退化成線性表地查詢log(n)。blog

相關文章
相關標籤/搜索