源碼閱讀之HashMap(JDK8)

概述

HashMap根據鍵的hashCode值存儲數據,大多數狀況下能夠直接定位到它的值,於是具備很快的訪問速度,但遍歷順序倒是不肯定的。 HashMap最多隻容許一條記錄的鍵爲null,容許多條記錄的值爲null。HashMap非線程安全,即任一時刻能夠有多個線程同時寫HashMap,可能會致使數據的不一致。node

內部結構

在jdk8中,HashMap處理「碰撞」增長了紅黑樹這種數據結構,當碰撞結點較少時,採用鏈表存儲,當較大時(>8個),採用紅黑樹(特色是查詢時間是O(logn))存儲(有一個閥值控制,大於閥值(8個),將鏈表存儲轉換成紅黑樹存儲)算法

數據結構

  1. 位桶數組數組

 transient Node<K,V>[] table;

  2.數組元素Node<K,V>實現了Entry接口安全

//Node是單向鏈表,它實現了Map.Entry接口  
static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;//用來定位數組索引位置
    final K key;
    V value;
    Node<K,V> next; // 下一個節點  

    //構造函數Hash值 鍵 值 下一個節點  
    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; }

  //每個節點的hash值,是將key的hashCode 和 value的hashCode 亦或獲得的。
public final int hashCode() { return Objects.hashCode(key) ^ Objects.hashCode(value); } public final V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; } //判斷兩個node是否相等,若key和value都相等,返回true。能夠與自身比較爲true 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; } }

  3. 紅黑樹數據結構

static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
    TreeNode<K,V> parent;  // 父節點 
    TreeNode<K,V> left; //左子樹  
    TreeNode<K,V> right; //右子樹  
    TreeNode<K,V> prev;    // needed to unlink next upon deletion
    boolean red; //顏色屬性  
    TreeNode(int hash, K key, V val, Node<K,V> next) {
        super(hash, key, val, next);
    }

    /**
     * Returns root of tree containing this node.
     * 返回當前節點的根節點
     */
    final TreeNode<K,V> root() {
        for (TreeNode<K,V> r = this, p;;) {
            // 一層一層往上找
            if ((p = r.parent) == null)
                return r;
            r = p;
        }
    }

源碼閱讀

  1. 基本元素app

//默認初始容量爲16,這裏這個數組的容量必須爲2的n次冪。
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 
    //最大容量爲2的30次方
    static final int MAXIMUM_CAPACITY = 1 << 30; 
    //默認加載因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    //以Node<K,V>爲元素的數組,長度是2的N次方,或者初始化時爲0.
    transient Node<K,V>[] table;
    // 鏈表->紅黑樹閥值
    static final int TREEIFY_THRESHOLD = 8; 
    // 紅黑樹->鏈表閥值
    static final int UNTREEIFY_THRESHOLD = 6; 
    // 紅黑樹樹化的最小表容量,最好>4*TREEIFY_THRESHOLD
    static final int MIN_TREEIFY_CAPACITY = 64; 
    //已經儲存的Node<key,value>的數量,包括數組中的和鏈表中的
    transient int size;
    //擴容的臨界值,或者所能容納的key-value對的極限。當size>threshold的時候就會擴容
    int threshold;
    //加載因子,用於計算哈希表元素數量的閾值。 threshold = 哈希桶.length * loadFactor;
    final float loadFactor;

  2.構造函數函數

public HashMap(int initialCapacity, float loadFactor) {
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal initial capacity: " +
                                           initialCapacity);
    if (initialCapacity > MAXIMUM_CAPACITY)
        initialCapacity = MAXIMUM_CAPACITY;
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal load factor: " +
                                           loadFactor);
    this.loadFactor = loadFactor;
    this.threshold = tableSizeFor(initialCapacity); //新的擴容臨界值  
}

public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
//根據指望容量cap,返回2的n次方形式的 哈希桶的實際容量 length。 返回值通常會>=cap    
static final int tableSizeFor(int cap) {
    //通過下面的 或 和位移 運算, n最終各位都是1。
int n = cap - 1; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16;
    //判斷n是否越界,返回 2的n次方做爲 table(哈希桶)的閾值
return (n < 0) ? 1 : (n >= 1 << 30) ? 1 << 30 : n + 1; }

這個方法就是算>=cap,且是2的倍數的最小值,例如性能

肯定哈希桶數組索引位置

無論增長、刪除、查找鍵值對,定位到哈希桶數組的位置都是很關鍵的第一步。前面說過HashMap的數據結構是數組和鏈表的結合,因此咱們固然但願這個HashMap裏面的元素位置儘可能分佈均勻些,儘可能使得每一個位置上的元素數量只有一個,那麼當咱們用hash算法求得這個位置的時候,立刻就能夠知道對應位置的元素就是咱們要的,不用遍歷鏈表,大大優化了查詢的效率。HashMap定位數組索引位置,直接決定了hash方法的離散性能。優化

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

//第二步
(n - 1) & hash

這裏的Hash算法本質上就是三步:取key的hashCode值、高位運算、取模運算this

經過hashCode()的高16位異或低16位實現的:(h = k.hashCode()) ^ (h >>> 16),主要是從速度、功效、質量來考慮的,這麼作能夠在數組table的length比較小的時候,也能保證考慮到高低Bit都參與到Hash的計算中,同時不會有太大的開銷。

經過(n - 1) & hash來獲得該對象的保存位,而HashMap底層數組的長度老是2的n次方,這是HashMap在速度上的優化。當length老是2的n次方時,(n - 1) & hash運算等價於對n取模,也就是h%n,可是&比%具備更高的效率。

添加元素

 

①.判斷鍵值對數組table[i]是否爲空或爲null,不然執行resize()進行擴容;

②.根據鍵值key計算hash值獲得插入的數組索引i,若是table[i]==null,直接新建節點添加,轉向⑥,若是table[i]不爲空,轉向③;

③.判斷table[i]的首個元素是否和key同樣,若是相同直接覆蓋value,不然轉向④,這裏的相同指的是hashCode以及equals;

④.判斷table[i] 是否爲treeNode,即table[i] 是不是紅黑樹,若是是紅黑樹,則直接在樹中插入鍵值對,不然轉向⑤;

⑤.遍歷table[i],判斷鏈表長度是否大於8,大於8的話把鏈表轉換爲紅黑樹,在紅黑樹中執行插入操做,不然進行鏈表的插入操做;遍歷過程當中若發現key已經存在直接覆蓋value便可;

⑥.插入成功後,判斷實際存在的鍵值對數量size是否超多了最大容量threshold,若是超過,進行擴容。

1     public V put(K key, V value) {
 2     // 對key的hashCode()作hash
 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; Node<K,V> p; int n, i;
 9     // 步驟①:tab爲空則建立
10     if ((tab = table) == null || (n = tab.length) == 0)
11         n = (tab = resize()).length;
12     // 步驟②:計算index,並對null作處理 
13     if ((p = tab[i = (n - 1) & hash]) == null) 
14         tab[i] = newNode(hash, key, value, null);
15     else {
16         Node<K,V> e; K k;
17         // 步驟③:節點key存在,直接覆蓋value
18         if (p.hash == hash &&
19             ((k = p.key) == key || (key != null && key.equals(k))))
20             e = p;
21         // 步驟④:判斷該鏈爲紅黑樹
22         else if (p instanceof TreeNode)
23             e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
24         // 步驟⑤:該鏈爲鏈表
25         else {
26             for (int binCount = 0; ; ++binCount) {
27                 if ((e = p.next) == null) {
28                     p.next = newNode(hash, key,value,null);
                        //鏈表長度大於8轉換爲紅黑樹進行處理
29                     if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st  
30                         treeifyBin(tab, hash);
31                     break;
32                 }
                    // key已經存在直接覆蓋value
33                 if (e.hash == hash &&
34                     ((k = e.key) == key || (key != null && key.equals(k))))                                           
             break; 36 p = e; 37 } 38 } 39 //若是e不是null,說明有須要覆蓋的節點, 40 if (e != null) { // existing mapping for key 41 V oldValue = e.value; 42 if (!onlyIfAbsent || oldValue == null) 43 e.value = value; 44 afterNodeAccess(e); 45 return oldValue; 46 } 47 } 48 ++modCount; 49 // 步驟⑥:超過最大容量 就擴容 50 if (++size > threshold) 51 resize(); 52 afterNodeInsertion(evict); 53 return null; 54 }

擴容機制

擴容(resize)就是從新計算容量,向HashMap對象裏不停的添加元素,而HashMap對象內部的數組沒法裝載更多的元素時,對象就須要擴大數組的長度,以便能裝入更多的元素。固然Java裏的數組是沒法自動擴容的,方法是使用一個新的數組代替已有的容量小的數組,就像咱們用一個小桶裝水,若是想裝更多的水,就得換大水桶。經過擴容也能夠有效的解決碰撞問題。

   final Node<K,V>[] resize() {
        //oldTab 爲當前表的哈希桶
        Node<K,V>[] oldTab = table;
        //當前哈希桶的容量 length
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        //當前的閾值
        int oldThr = threshold;
        //初始化新的容量和閾值爲0
        int newCap, newThr = 0;
        //若是當前容量大於0
        if (oldCap > 0) {
            //若是當前容量已經到達上限
            if (oldCap >= MAXIMUM_CAPACITY) {
                //則設置閾值是2的31次方-1
                threshold = Integer.MAX_VALUE;
                //同時返回當前的哈希桶,再也不擴容
                return oldTab;
            }//不然新的容量爲舊的容量的兩倍。 
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)//若是舊的容量大於等於默認初始容量16
                //那麼新的閾值也等於舊的閾值的兩倍
                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;//此時新表的容量爲默認的容量 16
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//新的閾值爲默認容量16 * 默認加載因子0.75f = 12
        }
        if (newThr == 0) {//若是新的閾值是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) {
                //取出當前的節點 e
                Node<K,V> e;
                //若是當前桶中有元素,則將鏈表賦值給e
                if ((e = oldTab[j]) != null) {
                    //將原哈希桶置空以便GC
                    oldTab[j] = null;
                    //若是當前鏈表中就一個元素,(沒有發生哈希碰撞)
                    if (e.next == null)
                        //直接將這個元素放置在新的哈希桶裏。
                        //注意這裏取下標 是用 哈希值 與 桶的長度-1 。 因爲桶的長度是2的n次方,這麼作實際上是等於 一個模運算。可是效率更高
                        newTab[e.hash & (newCap - 1)] = e;
                        //若是發生過哈希碰撞 ,並且是節點數超過8個,轉化成了紅黑樹(暫且不談 避免過於複雜, 後續專門研究一下紅黑樹)
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    //若是發生過哈希碰撞,節點數小於8個。則要根據鏈表上每一個節點的哈希值,依次放入新哈希桶對應下標位置。
                    else { // preserve order
                        //由於擴容是容量翻倍,因此原鏈表上的每一個節點,如今可能存放在原來的下標,即low位, 或者擴容後的下標,即high位。 high位=  low位+原哈希桶容量
                        //低位鏈表的頭結點、尾節點
                        Node<K,V> loHead = null, loTail = null;
                        //高位鏈表的頭節點、尾節點
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;//臨時節點 存放e的下一個節點
                        do {
                            next = e.next;
                            //這裏又是一個利用位運算 代替常規運算的高效點: 利用哈希值 與 舊的容量,能夠獲得哈希值去模後,是大於等於oldCap仍是小於oldCap,等於0表明小於oldCap,應該存放在低位,不然存放在高位
                            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);
                        //將低位鏈表存放在原index處,
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        //將高位鏈表存放在新index處
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

 查詢元素

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

   
     final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        // 找到hash對應的位置,也就是數組中的位置
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            // 檢查第一個Node是否是要找的Node
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
                // 檢查first後面的node
              if ((e = first.next) != null) {
                if (first instanceof TreeNode) // 查詢紅黑樹
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    // 遍歷後面的鏈表,找到key值和hash值都相同的Node
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }
相關文章
相關標籤/搜索