java HashMap源碼分析(JDK8)

  這兩天在複習JAVA的知識點,想更深層次的瞭解一下JAVA,因此就看了看JAVA的源碼,把本身的分析寫在這裏,也當作是筆記吧,方便記憶。寫的不對的地方也請你們多多指教。node

  JDK1.6中HashMap採用的是位桶+鏈表的方式,即咱們常說的散列鏈表的方式,而JDK1.8中採用的是位桶+鏈表/紅黑樹的方式,也是非線程安全的。當某個位桶的鏈表的長度達到某個閥值的時候,這個鏈表就將轉換成紅黑樹。數組

基本的數據結構:安全

 1 //鏈表節點
 2 static class Node<K,V> implements Map.Entry<K,V> {
 3         final int hash;
 4         final K key;
 5         V value;
 6         Node<K,V> next;
 7      //省略 
 8 }
 9 //紅黑樹節點
10 static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
11         TreeNode<K,V> parent;  // red-black tree links
12         TreeNode<K,V> left;
13         TreeNode<K,V> right;
14         TreeNode<K,V> prev;    // needed to unlink next upon deletion
15         boolean red;
16         TreeNode(int hash, K key, V val, Node<K,V> next) {
17             super(hash, key, val, next);
18         }
19         //省略  
20 }
21 // HashMap的主要屬性
22 public class HashMap<K,V> extends AbstractMap<K,V>
23     implements Map<K,V>, Cloneable, Serializable {
24     // 槽數組,Node<K,V>類型,TreeNode extends LinkedHashMap.Entry<K,V>,因此能夠存放TreeNode來實現Tree bins
25     transient Node<K,V>[] table;
26     
27     transient Set<Map.Entry<K,V>> entrySet;
28 
29     transient int size;
30     // 去掉了volatile的修飾符
31     transient int modCount;
32 
33     int threshold;
34 
35     final float loadFactor;
36 
37     ...
38 
39 }
   

 

//計算key的hash
static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
 }

 get(key) 函數數據結構

 1 public V get(Object key) {
 2         Node<K,V> e;
 3         return (e = getNode(hash(key), key)) == null ? null : e.value;
 4     }
 5      final Node<K,V> getNode(int hash, Object key) {
 6             Node<K,V>[] tab; 
 7             Node<K,V> first, e; 
 8             int n; K k;
 9             //hash & length-1 定位數組下標
10             if ((tab = table) != null && (n = tab.length) > 0 &&
11                 (first = tab[(n - 1) & hash]) != null) 
12             {
13                 if (first.hash == hash && // always check first node
14                     ((k = first.key) == key || (key != null && key.equals(k))))
15                     return first;
16                 if ((e = first.next) != null) {
17                     /*第一個節點是TreeNode,則採用位桶+紅黑樹結構,
18                      * 調用TreeNode.getTreeNode(hash,key),
19                      *遍歷紅黑樹,獲得節點的value
20                      */
21                     if (first instanceof TreeNode)
22                         return ((TreeNode<K,V>)first).getTreeNode(hash, key);
23                     do {
24                         if (e.hash == hash &&
25                             ((k = e.key) == key || (key != null && key.equals(k))))
26                             return e;
27                        } while ((e = e.next) != null);
28                 }
29             }
30             return null;
31         }
32      final TreeNode<K,V> getTreeNode(int h, Object k) {
33              //找到紅黑樹的根節點並遍歷紅黑樹
34          return ((parent != null) ? root() : this).find(h, k, null);
35      }
36      /*
37       *經過hash值的比較,遞歸的去遍歷紅黑樹,這裏要提的是compareableClassFor(Class k)這個函數的做用,在某些時候
38       *若是紅黑樹節點的元素are of the same "class C implements Comparable<C>" type 
39       *利用他們的compareTo()方法來比較大小,這裏須要經過反射機制來check他們究竟是不是屬於同一個類,是否是具備可比較性.
40       */
41      final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
42          TreeNode<K,V> p = this;
43          do {
44              int ph, dir; K pk;
45              TreeNode<K,V> pl = p.left, pr = p.right, q;
46              if ((ph = p.hash) > h)
47                  p = pl;
48              else if (ph < h)
49                  p = pr;
50              else if ((pk = p.key) == k || (k != null && k.equals(pk)))
51                  return p;
52              else if (pl == null)
53                  p = pr;
54              else if (pr == null)
55                  p = pl;
56              else if ((kc != null ||
57                        (kc = comparableClassFor(k)) != null) &&
58                       (dir = compareComparables(kc, k, pk)) != 0)
59                  p = (dir < 0) ? pl : pr;
60              else if ((q = pr.find(h, k, kc)) != null)
61                  return q;
62              else
63                  p = pl;
64          } while (p != null);
65          return null;
66      }      

put(K key,V value)函數 app

 1 //put(K key,V value)函數 
 2     public V put(K key, V value) {
 3             return putVal(hash(key), key, value, false, true);
 4         }
 5     
 6     final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
 7             boolean evict) {
 8          Node<K,V>[] tab; 
 9          Node<K,V> p; 
10          int n, i;
11          //若是table爲空或者長度爲0,則resize()
12          if ((tab = table) == null || (n = tab.length) == 0)
13              n = (tab = resize()).length;
14          //找到key值對應的槽而且是第一個,直接加入
15          if ((p = tab[i = (n - 1) & hash]) == null)
16              tab[i] = newNode(hash, key, value, null);
17          else {
18                  Node<K,V> e;
19                  K k;
20                  //第一個node的hash值即爲要加入元素的hash
21                  if (p.hash == hash &&
22                      ((k = p.key) == key || (key != null && key.equals(k)))){
23                       e = p;
24                  }else if (p instanceof TreeNode)//第一個節點是TreeNode,即tree-bin
25                     /*Tree version of putVal.
26                      *final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,int h, K k, V v)
27                      */
28                      e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
29                      else {
30                          //不是TreeNode,即爲鏈表,遍歷鏈表
31                          for (int binCount = 0; ; ++binCount) {
32                              /*到達鏈表的尾端也沒有找到key值相同的節點,
33                               *則生成一個新的Node,而且判斷鏈表的節點個數是否是到達轉換成紅黑樹的上界
34                               *達到,則轉換成紅黑樹
35                               */
36                              if ((e = p.next) == null) {
37                                  p.next = newNode(hash, key, value, null);
38                                  if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
39                                      treeifyBin(tab, hash);
40                                  break;
41                              }
42                              if (e.hash == hash &&
43                                  ((k = e.key) == key || (key != null && key.equals(k))))
44                                  break;
45                              p = e;
46                          }
47                      }
48                  if (e != null) { // existing mapping for key
49                      V oldValue = e.value;
50                      if (!onlyIfAbsent || oldValue == null)
51                          e.value = value;
52                      afterNodeAccess(e);
53                      //返回舊的value值
54                      return oldValue;
55                  }
56          }
57          ++modCount;
58          if (++size > threshold)
59              resize();
60          afterNodeInsertion(evict);
61          return null;
62 }
相關文章
相關標籤/搜索