HashMap的put()與擴容

1. put()

 1 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
 2                    boolean evict) {
 3         HashMap.Node<K,V>[] tab;//指向存儲數組的引用
 4         HashMap.Node<K,V> p;
 5         int n, i;//n是數組長度,i是插入值的存儲下標
 6         //判斷存儲數組是否爲空,即數組是否初始化
 7         if ((tab = table) == null || (n = tab.length) == 0)
 8             n = (tab = resize()).length;
 9         //計算出存儲下標,並將數組中下標與插入值位置相同的賦給p
10         if ((p = tab[i = (n - 1) & hash]) == null)
11             //若是p爲null則表示插入值的插入位置沒有值,則直接插入
12             tab[i] = newNode(hash, key, value, null);
13         //p!=null
14         else {
15             HashMap.Node<K,V> e;
16             K k;
17             //判斷p的key是否與插入值的key相等,若是相等,則不須要插入
18             if (p.hash == hash &&
19                     ((k = p.key) == key || (key != null && key.equals(k))))
20                 e = p;
21             //若是p是紅黑樹節點
22             else if (p instanceof HashMap.TreeNode)
23                 //直接將值插入到紅黑樹中,在紅黑樹的插入中一樣會進行key是否存在的判斷,若是有則返回那個節點,不然返回null
24                 e = ((HashMap.TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
25             //p是鏈表節點
26             else {
27                 //遍歷鏈表
28                 for (int binCount = 0; ; ++binCount) {
29                     //若是鏈表到頭了,則將當前值插入到鏈表中
30                     if ((e = p.next) == null) {
31                         //插入
32                         p.next = newNode(hash, key, value, null);
33                         //判斷鏈表的長度是否達到變成紅黑樹的長度
34                         if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
35                             //變成紅黑樹
36                             treeifyBin(tab, hash);
37                         //若是從這裏break出去,e的值就爲null
38                         break;
39                     }
40                     //若是鏈表中存在key與插入值的key相同的節點,break
41                     if (e.hash == hash &&
42                             ((k = e.key) == key || (key != null && key.equals(k))))
43                         break;
44                     p = e;
45                 }
46             }
47             //e!=null表示map中存在key與插入值的key相同,則更新值就行
48             if (e != null) { // existing mapping for key
49                 V oldValue = e.value;
50                 if (!onlyIfAbsent || oldValue == null)
51                     e.value = value;
52                 //對於HashMap來講是空函數,沒有意義,LinkedHashMap中才有用
53                 afterNodeAccess(e);
54                 return oldValue;
55             }
56         }
57         //modCount是數組實際插入次數(根據代碼來看,若是沒有插入,只是更新的話是不會增長的)
58         ++modCount;
59         //size是map中的元素個數(包括鏈表,紅黑樹以及數組上的元素),thresold是擴容閾值,若是達到這個值則擴容
60         if (++size > threshold)
61             resize();
62         //對於HashMap來講是空函數,沒有意義,LinkedHashMap中才有用
63         afterNodeInsertion(evict);
64         return null;
65     }

2. 擴容

  待更新....數組

相關文章
相關標籤/搜索