1. 程式人生 > >JDK1.8原始碼解讀——HashMap原始碼

JDK1.8原始碼解讀——HashMap原始碼

從類的Doc文件註釋中,我們可以得出HashMap的一些特性:
  1 無序 允許為null 非同步
  2 底層由雜湊表實現
  3 初始容量和負載因子對HashMap的影響很大
成員變數:

   /**預設初始值,必須是二的倍數 */
   static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 
   /** 最大容量 */
   static final int MAXIMUM_CAPACITY = 1 << 30;
   /**預設的負載因子 */
   static final float DEFAULT_LOAD_FACTOR =
0.75f; /**閾值,一個雜湊桶被新增到TREEIFY_THRESHOLD個節點的時候,桶中的連結串列會被轉化為紅黑二叉樹 */ static final int TREEIFY_THRESHOLD = 8; /** 閾值,將紅黑二叉樹轉化成連結串列(紅黑二叉樹為了保持平衡,要進行左旋,右旋,換色,消耗資源)*/ static final int UNTREEIFY_THRESHOLD = 6; /**桶可能被樹化為樹形結構的最小容量*/ static final int MIN_TREEIFY_CAPACITY = 64;

儲存結構:
HashMap內部包含了一個Node型別的陣列table,Node即為 JDK1.8之前的Entry

transient Node<K,V>[] table;
/**
* Basic hash bin node, used for most entries.  (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
*/
static class Node<K,V> implements Map.Entry<K,V> {
 final int hash;
 final K key;
 V value;
 Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } public final K getKey() { return key; } public final V getValue() { return value; } public final String toString() { return key + "=" + value; } public final int hashCode() { return Objects.hashCode(key) ^ Objects.hashCode(value); } public final V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; } public final boolean equals(Object o) { if (o == this) return true; if (o instanceof Map.Entry) { Map.Entry<?,?> e = (Map.Entry<?,?>)o; if (Objects.equals(key, e.getKey()) && Objects.equals(value, e.getValue())) return true; } return false; } }

結論:
  Node裡儲存的是鍵值對。包含四個欄位,從next欄位我們可以看出Node是一個連結串列。
即table陣列中每個位置被當成一個桶,一個桶用來存放一個連結串列Node。
  HashMap使用拉鍊法來解決衝突(ThreadLocalMap則是採用線性探測法),同一個連結串列存放key的雜湊值相同的Node
1 put方法(HashMap的核心):

public V put(K key, V value) {
  return putVal(hash(key), key, value, false, true);
}

hash後的key,key Value ,兩個引數

首先,看一下hash方法

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

結論:
  int 一共32位,這裡作者將其分成前16位和後16位。取key的hashcode,與keyhashCode的高16位做異或。這裡是將低16位與高16位做運算,得到的值實際上是高位和低位的結合,這就增加了隨機性。在一定程度上減少了雜湊衝突的發生。這裡hashCode是呼叫的Object中的hashCode,即引用物件的hashcode與其記憶體地址有關

/**
* Implements Map.put and related methods
*
* @param key的雜湊值
* @param key 鍵
* @param value 要放入的值
* @param onlyIfAbsent true 則不改變現有值,預設是false
* @param evict 如果是false,則表處於建立模式,預設是true
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
             boolean evict) {
  Node<K,V>[] tab; Node<K,V> p; int n, i;
  if ((tab = table) == null || (n = tab.length) == 0)
      n = (tab = resize()).length;
 //如果散列表為null,則初始化散列表
  if ((p = tab[i = (n - 1) & hash]) == null)
      tab[i] = newNode(hash, key, value, null);
  //將物件放入散列表的時,預設初始容量是16,也就是說,要放到table陣列的0-15的位置上,所以通過tab[i = (n - 1) & hash]來確定陣列下標位置,n如果為奇數,則n-1為偶數,0與任何數的&運算都是0,會造成一部分的記憶體浪費(下標最後一位為0的位置存不會存值)
  //如果沒有發生雜湊衝突,則直接將新建的Entry物件放入table陣列中
  else {
      Node<K,V> e; K k;
      if (p.hash == hash &&
          ((k = p.key) == key || (key != null && key.equals(k))))
          e = p;
//如果發生了雜湊衝突,就先記錄下發生衝突的Node
      else if (p instanceof TreeNode)
          e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
   //如果紅黑樹結構,則呼叫紅合數的插入方法
      else {
          for (int binCount = 0; ; ++binCount) {
              if ((e = p.next) == null) {
          //如果遍歷連結串列沒有發現該此節點,就插入連結串列的尾部(尾插法,1.8之前都是頭插法)
                  p.next = newNode(hash, key, value, null);
          //如果插入後連結串列長度大於8,則轉換為紅黑樹
                  if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                      treeifyBin(tab, hash);
                  break;
              }
         //如果key在連結串列中已經存在,則退出迴圈
              if (e.hash == hash &&
                  ((k = e.key) == key || (key != null && key.equals(k))))
                  break;
              p = e;
          }
      }
   //如果key在連結串列中已經存在,則修改其原先的key值,並且返回老的值
      if (e != null) { // existing mapping for key
          V oldValue = e.value;
          if (!onlyIfAbsent || oldValue == null)
              e.value = value;
          afterNodeAccess(e);
          return oldValue;
      }
  }
  ++modCount;
  if (++size > threshold)
      resize();
  afterNodeInsertion(evict);
  return null;
}

2 resize()方法:是HashMap的擴容方法,新的容量是舊的容量的兩倍,需要注意的是,擴容操作同樣需要把 oldTable 的所有鍵值對重新插入 newTable 中,因此這一步是很費時的。

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) {
                    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);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

3 get方法

public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}

通過key計算雜湊值,呼叫getNode()來獲取對應的value

/**
 * Implements Map.get and related methods
 *
 * @param hash hash for key
 * @param key the key
 * @return the node, or null if none
 */
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) {
    //判斷計算出來的hash值是否在散列表上
 
        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;
}

4 remove方法:從此對映中刪除指定鍵的對映(如果存在)

public V remove(Object key) {
   Node<K,V> e;
   return (e = removeNode(hash(key), key, null, false, true)) == null ?
       null : e.value;
}
通過key計算雜湊值,呼叫removeNode()來刪除節點

final Node<K,V> removeNode(int hash, Object key, Object value,
                          boolean matchValue, boolean movable) {
   Node<K,V>[] tab; Node<K,V> p; int n, index;
   if ((tab = table) != null && (n = tab.length) > 0 &&
       (p = tab[index = (n - 1) & hash]) != null) {
    //同get,判斷計算出來的hash值是否在散列表上
       Node<K,V> node = null, e; K k; V v;
       if (p.hash == hash &&
           ((k = p.key) == key || (key != null && key.equals(k))))
           node = p;
    //先查詢首位,如果可以找到,就記錄下來
       else if ((e = p.next) != null) {
           if (p instanceof TreeNode)
               node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
           else {
               do {
                   if (e.hash == hash &&
                       ((k = e.key) == key ||
                        (key != null && key.equals(k)))) {
                       node = e;
                       break;
                   }
                   p = e;
               } while ((e = e.next) != null);
           }
       }
   //不是在首位,就去紅黑樹或者連結串列中查詢,如果可以找到就記錄下來

       if (node != null && (!matchValue || (v = node.value) == value ||
                            (value != null && value.equals(v)))) {
           if (node instanceof TreeNode)
               ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
           else if (node == p)
               tab[index] = node.next;
           else
               p.next = node.next;
           ++modCount;
           --size;
           afterNodeRemoval(node);
           return node;
      //找到了對應的節點,並且value值對應上了,那麼就可以刪除了,這裡也分三種情況,在連結串列,在紅黑樹,在桶的首位
       }
   }
   return null;
}

參考資料:
jdk1.8原始碼
https://github.com/CyC2018/CS-Notes/blob/master/notes/Java 容器.md#hashmap
大牛部落格
https://blog.csdn.net/qq_33256688/article/details/79938886
HashMap到底是插入連結串列頭部還是尾部