HashMap 源碼分析

簡介

JDK1.7:

1.數(shù)據(jù)結(jié)構(gòu)是數(shù)組加鏈表
2.在并發(fā)的情況,發(fā)生擴(kuò)容時(shí),可能會(huì)產(chǎn)生循環(huán)鏈表,在執(zhí)行g(shù)et的時(shí)候,會(huì)觸發(fā)死循環(huán),引起CPU的100%問題
3.在并發(fā)的情況會(huì)產(chǎn)生數(shù)據(jù)丟失

JDK1.8

1.數(shù)據(jù)結(jié)構(gòu)是數(shù)組加鏈表、紅黑樹
2.在并發(fā)的情況會(huì)產(chǎn)生數(shù)據(jù)丟失

數(shù)據(jù)結(jié)構(gòu)

hashMap1.png
Hash散列結(jié)構(gòu)

用于將 key 的 hashCode 映射為數(shù)組上的角標(biāo)

// 拿到key的hash值后與其無符號(hào)右移16位取與
// 通過這種方式,讓高位數(shù)據(jù)與低位數(shù)據(jù)進(jìn)行異或,以此加大低位信息的隨機(jī)性,變相的讓高位數(shù)據(jù)參與到計(jì)算中。
 static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
// 獲取到處理后的Hash值后計(jì)算數(shù)組中的位置
// n 為數(shù)組的長度即 length,index 為數(shù)組中的位置
index = hash % n

//和上面的算法相同,但效率高
index = (n - 1) & hash 

為什么 hash 對(duì) length 取余就能得到數(shù)組角標(biāo)?
因?yàn)?hash 對(duì)數(shù)組的長度取余,那么得到的數(shù)一定在數(shù)組長度范圍之內(nèi)

所以 index 和數(shù)組長度有關(guān)
這也是為什么當(dāng)數(shù)組長度變化后,所有的元素都要重新計(jì)算位置。

數(shù)組結(jié)構(gòu):

存儲(chǔ)鏈表或紅黑樹的首個(gè)節(jié)點(diǎn)

單向鏈表結(jié)構(gòu):
static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;
    //構(gòu)造函數(shù)
    Node(int hash, K key, V value, Node<K,V> next) {
        this.hash = hash;
        this.key = key;
        this.value = value;
        this.next = next;
    }

    // getter and setter ... toString ...
    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;
    }
}

紅黑樹結(jié)構(gòu):

LinkedHashMap.Entry 繼承自 HashMap.Node ,所以 TreeNode 繼承自 上面鏈表結(jié)構(gòu)的 Node

static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
    TreeNode<K,V> parent;  // red-black tree links
    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;
        }
    }

源碼分析

變量說明

注意:這里的容量指的是數(shù)組的容量也是HashMap的容量,而 size 字段則代表HashMap當(dāng)前存儲(chǔ)的數(shù)據(jù)量,即HashMap中鍵值對(duì)的數(shù)量

/**
 * 默認(rèn)初始容量16(必須是2的冪次方)
 */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;

/**
 * 最大容量,2的30次方
 */
static final int MAXIMUM_CAPACITY = 1 << 30;

/**
 * 默認(rèn)加載因子,用來計(jì)算threshold
 */
static final float DEFAULT_LOAD_FACTOR = 0.75f;

/**
 * 鏈表轉(zhuǎn)成樹的閾值,當(dāng)桶中鏈表長度大于等于8時(shí)轉(zhuǎn)成樹 
 */
static final int TREEIFY_THRESHOLD = 8;

/**
 * 進(jìn)行resize操作時(shí),若桶中數(shù)量小于等于6則從樹轉(zhuǎn)成鏈表
 */
static final int UNTREEIFY_THRESHOLD = 6;

/**
 * 桶中結(jié)構(gòu)轉(zhuǎn)化為紅黑樹對(duì)應(yīng)的table的最小大小

 當(dāng)需要將解決 hash 沖突的鏈表轉(zhuǎn)變?yōu)榧t黑樹時(shí),
 需要判斷下此時(shí)數(shù)組容量,
 若是由于數(shù)組容量太小(小于 MIN_TREEIFY_CAPACITY?。? 導(dǎo)致的 hash 沖突太多,則不進(jìn)行鏈表轉(zhuǎn)變?yōu)榧t黑樹操作,
 轉(zhuǎn)為利用 resize() 函數(shù)對(duì) hashMap 擴(kuò)容
 */
static final int MIN_TREEIFY_CAPACITY = 64;
/**
 保存Node<K,V>節(jié)點(diǎn)的數(shù)組
 該表在首次使用時(shí)初始化,并根據(jù)需要調(diào)整大小。 分配時(shí),
 長度始終是2的冪。
 */
transient Node<K,V>[] table;

/**
 * 存放具體元素的集
 */
transient Set<Map.Entry<K,V>> entrySet;

/**
 * 記錄 hashMap 當(dāng)前存儲(chǔ)的元素的數(shù)量
 */
transient int size;

/**
 * 每次更改map結(jié)構(gòu)的計(jì)數(shù)器
 */
transient int modCount;

/**
 * 用于判斷是否需要擴(kuò)容
 * threshold = capacity * loadFactor
 * 
 * 如果 size > threshold 則進(jìn)行擴(kuò)容
 * 這里的size是指HashMap 的size不是數(shù)組的長度
 *
 */
int threshold;

/**
 * 加載因子:用于計(jì)算threshold
 */
final float loadFactor;

HashMap 添加元素:
hashMap2.png
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;

        //判斷數(shù)組是否為空,如果為空則重新初始化數(shù)組
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //判斷當(dāng)前 hash 計(jì)算后數(shù)組位置上的元素是否為空
        if ((p = tab[i = (n - 1) & hash]) == null)
            //當(dāng)前位置沒有元素這直接將 Node 放入即可
            tab[i] = newNode(hash, key, value, null);
        else {
            //該位置已經(jīng)有元素了,解決hash碰撞

            Node<K,V> e; K k;
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                //當(dāng)前傳入的key 和 當(dāng)前位置上的key 是同一個(gè),說明只要修改值就行了
                e = p;
            else if (p instanceof TreeNode)
                //當(dāng)前傳入的key 和 當(dāng)前位置上的key 不是同一個(gè),且當(dāng)前節(jié)點(diǎn)為紅黑樹節(jié)點(diǎn),將傳入的元素加入紅黑樹
                e = ((HashMap.TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                //當(dāng)前傳入的key 和 當(dāng)前位置上的key 不是同一個(gè),且當(dāng)前節(jié)點(diǎn)不是紅黑樹,那就是鏈表結(jié)構(gòu)
                //遍歷鏈表,插入傳入的元素
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        // 如果p的next為空,將傳入的元素添加到鏈表后面
                        p.next = newNode(hash, key, value, null);
                        //如果鏈表長度大于等于8 則轉(zhuǎn)化為紅黑樹
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //判斷傳入的元素已經(jīng)添加到鏈表最后一個(gè)節(jié)點(diǎn),中斷循環(huán)
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                //根據(jù)規(guī)則選擇是否覆蓋value
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        // size自增后大于擴(kuò)容閾值,進(jìn)行擴(kuò)容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

首先根據(jù)key的哈希值計(jì)算出 Node 應(yīng)該存放在數(shù)組什么位置
但是可能會(huì)出現(xiàn)哈希沖突,所以當(dāng)兩個(gè)不同的key
其哈希是一樣的,那么他們存放在數(shù)組中的位置就是相同的,這時(shí)候會(huì)將這兩個(gè)Node用鏈表的結(jié)構(gòu)存放,但是當(dāng)數(shù)組中一個(gè)位置的鏈表元素大于等于8個(gè)時(shí),鏈表插入的效率貶低,此時(shí)鏈表結(jié)構(gòu)會(huì)轉(zhuǎn)換為紅黑樹

[圖片上傳失敗...(image-c2ec54-1664265469619)]

擴(kuò)容機(jī)制

添加元素時(shí),如果 size > threshold 則進(jìn)行擴(kuò)容,size 為HashMap當(dāng)前存儲(chǔ)的數(shù)據(jù)量,

  final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;//默認(rèn)值為0,如果在HashMap構(gòu)造函數(shù)中傳入了數(shù)組的容量,會(huì)給 threshold 賦值
        int newCap, newThr = 0;
        
        /* ① 根據(jù)原先數(shù)組的容量和閾值計(jì)算新的容量和閾值 **/
        if (oldCap > 0) {//數(shù)組容量大于0 
            if (oldCap >= MAXIMUM_CAPACITY) {//數(shù)組容量大于等于最大值,不進(jìn)行擴(kuò)容了
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //擴(kuò)容一倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                //如果擴(kuò)容后小于最大值 而且 舊數(shù)組桶大于初始容量16, 閾值左移1(擴(kuò)大為原有的2倍)   
                newThr = oldThr << 1; // double threshold
        }
        // 下面情況是數(shù)組容量小于等于0,說明數(shù)組還未被初始化
        
        else if (oldThr > 0) // HashMap構(gòu)造函數(shù)中傳入了指定容量,使用指定容量初始化數(shù)組
            newCap = oldThr;
        else {               // oldThr小于等于0,數(shù)組使用默認(rèn)容量初始化數(shù)組
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        
        /* ② 創(chuàng)建新的數(shù)組,更新 threshold 和 數(shù)組 **/
        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;
        
        /* ③ 遍歷原數(shù)組,將數(shù)據(jù)添加到新數(shù)組中 **/
        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) // 該節(jié)點(diǎn)無其他關(guān)聯(lián)節(jié)點(diǎn)直接賦值到新數(shù)組
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode) // 如果為樹節(jié)點(diǎn),切割樹節(jié)點(diǎn),這時(shí)如果樹的大小小于等于6就會(huì)被轉(zhuǎn)成鏈表
                        ((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;
    }
① 計(jì)算擴(kuò)容后的容量和閾值
  1. HashMap已經(jīng)初始化(數(shù)組容量大于0)

    table的容量以及threshold量擴(kuò)大為原有的兩倍。
    newCap = oldCap * 2
    newThr = oldThr * 2
    
  2. 指定容量的構(gòu)造方法初始化HashMap(oldThr > 0)

    //指定容量和加載因子構(gòu)造函數(shù)
    public HashMap(int initialCapacity, float loadFactor) {
        ... ...
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }
    //取容量最接近2的次冪 的值,為閾值    
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }
    
    newCap = threshold
    newThr = newCap * loadFactor
    
  3. 默認(rèn)構(gòu)造方法初始化HashMap(oldThr = 0)

    newCap = DEFAULT_INITIAL_CAPACITY = 16
    newThr = DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR = 12
    
② 創(chuàng)建新數(shù)組

Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];

② 遷移數(shù)據(jù)至數(shù)組
  1. 節(jié)點(diǎn)無子節(jié)點(diǎn)
    直接重新計(jì)算該節(jié)點(diǎn)的index
    newTab[e.hash & (newCap - 1)] = e;
    
  2. 節(jié)點(diǎn)為鏈表
    因?yàn)镠ashMap的容量為2的倍數(shù),擴(kuò)容后也是擴(kuò)容一倍,所以不用重新計(jì)算index,
    只需要判斷 x = (e.hash & oldCap)
    
    x == 0 :說明 e 節(jié)點(diǎn)的hash值小于 oldCap,那么這些節(jié)點(diǎn)的 newIndex = oldIndex。
    
    x != 0 :說明 e 節(jié)點(diǎn)的hash值大于等于 oldCap,那么這些節(jié)點(diǎn)的 newIndex = (oldIndex + oldCap)
    
  3. 節(jié)點(diǎn)為紅黑樹
    和鏈表遷移方式相同,多了一步判斷紅黑樹大小如果小于等于6的話會(huì)轉(zhuǎn)換為鏈表結(jié)構(gòu)
    

擴(kuò)展

HashMap的大小為什么必須是2的倍數(shù)?

1.計(jì)算數(shù)組index時(shí),2的倍數(shù)會(huì)減少Hash沖突
# index 的算法,n 表示 HashMap 的容量

index = (n - 1) & hash 
n 為2的倍數(shù)
進(jìn)制 n = 8 (n-1) = 7 hash = 10
二進(jìn)制 0000 1000 0000 0111 0000 1010
# 計(jì)算hash為 10,11,12 的index

(n-1) & 10 = 0000 0010 = 2
(n-1) & 11 = 0000 0011 = 3
(n-1) & 12 = 0000 0100 = 4
n 不為2的倍數(shù)
進(jìn)制 n = 9 (n-1) = 8 hash = 10
二進(jìn)制 0000 1001 0000 1000 0000 1010
# 計(jì)算hash為 10,11,12 的index

(n-1) & 10 = 0000 1000 = 8
(n-1) & 11 = 0000 1000 = 8
(n-1) & 12 = 0000 1000 = 8

這里可以看出,n 如果是2的倍數(shù),n-1 則會(huì)將后置位的0全部變?yōu)?,如果 n 不為2的倍數(shù),則 n-1 的后置位可能存在0,那么無論 hash 值的二進(jìn)制位為 1 還是 0,&計(jì)算后的結(jié)果都為0,所以會(huì)增加hash沖突

2.每次擴(kuò)容都是擴(kuò)容一倍,所以擴(kuò)容后的大小也是2的倍數(shù),將已經(jīng)產(chǎn)生hash碰撞的元素轉(zhuǎn)移到新的table中時(shí)不用去重新計(jì)算index

假設(shè):

oldCap = 8 oldCap-1 newCap == 16 newCap-1
0000 1000 0000 0111 0001 0000 0000 1111
如果: hash < oldCap ,那么hash值的低位第4位一定為0
所以:hash & (oldCap-1) == hash & (newCap-1)
即:newIndex = oldIndex

如果: hash >= oldCap ,那么hash值的低位第4位一定為1
所以:(hash & (oldCap-1)) + oldCap == hash & (newCap-1)
即:newIndex = (oldIndex + oldCap)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 目錄 一、數(shù)據(jù)模型 二、重要屬性 三、構(gòu)造方法 四、普通方法 put() resize() get() 五、總結(jié) ...
    追夢1819閱讀 196評(píng)論 0 1
  • JAVA 8 HashMap 源碼分析 一 什么是HashMap? HashMap 繼承了AbstractMap,...
    gdutkyle閱讀 514評(píng)論 0 1
  • 1.HashMap的底層實(shí)現(xiàn)圖示 如上圖所示: HashMap底層是由數(shù)組+(鏈表)=(紅黑樹)組成,每個(gè)存儲(chǔ)在H...
    Bamboo_a67a閱讀 337評(píng)論 0 0
  • 感謝 shixinzhang的文章, 參考此:https://blog.csdn.net/u011240877/a...
    loveinthesweet閱讀 480評(píng)論 0 0
  • 本文從 Hash 方法開始,通過分析源碼,深入介紹了 JDK 不同版本中 HashMap 的實(shí)現(xiàn)。 HashMap...
    南風(fēng)過境jz閱讀 222評(píng)論 0 0

友情鏈接更多精彩內(nèi)容