徹底掌握HashMap的源碼實現(xiàn)

概述

  • HashMap是 Key-Value 對映射的抽象接口,該映射不包括重復(fù)的鍵,即一個鍵對應(yīng)一個值。
  • 在HashMap中,其會根據(jù)hash算法來計算key-value的存儲位置并進(jìn)行快速存取。
  • HashMap允許key和value為null
  • 當(dāng)Hash值計算元素位置時,可能會存在Hash沖突(Hash碰撞),HashMap是采用鏈表解決的。
  • HashMap的實現(xiàn),在JDK7中采用的是數(shù)組+鏈表,JDK8中采用的是數(shù)組+鏈表+紅黑樹。

HashMap源碼解讀(JDK8)

1.HashMap的結(jié)構(gòu)模型圖
HashMap的結(jié)構(gòu)模型圖
2. 了解HashMap的基本屬性
   /**
     * The default initial capacity - MUST be a power of two.
     * 初始map的容量大小為16(容量必須是2的冪次倍)
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     *  Map的最大容量為2的30次方
     *  java中存放的是補碼,1左移31位的為 16進(jìn)制的0x80000000代表的是-2147483648–>所以最大只能是30
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * The load factor used when none specified in constructor.
     * Map 容量的記載因子,主要影響map的在什么時候擴(kuò)容(此處為0.75,Map數(shù)組的容量大小的75%時開始擴(kuò)容)
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * The bin count threshold for using a tree rather than list for a
     * bin.  Bins are converted to trees when adding an element to a
     * bin with at least this many nodes. The value must be greater
     * than 2 and should be at least 8 to mesh with assumptions in
     * tree removal about conversion back to plain bins upon
     * shrinkage.
     *  當(dāng)桶(bucket)上的結(jié)點數(shù)大于這個值時會轉(zhuǎn)成紅黑樹
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * The bin count threshold for untreeifying a (split) bin during a
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     *  當(dāng)桶(bucket)上的結(jié)點數(shù)小于這個值時樹轉(zhuǎn)鏈表
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * The smallest table capacity for which bins may be treeified.
     * (Otherwise the table is resized if too many nodes in a bin.)
     * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
     * between resizing and treeification thresholds.
     * 桶中結(jié)構(gòu)轉(zhuǎn)化為紅黑樹對應(yīng)的table的最小大小
     */
    static final int MIN_TREEIFY_CAPACITY = 64;
     /**
     * The table, initialized on first use, and resized as
     * necessary. When allocated, length is always a power of two.
     * (We also tolerate length zero in some operations to allow
     * bootstrapping mechanics that are currently not needed.)
     *  存儲元素的table數(shù)組,容量總是2的冪次倍
     */
    transient Node<K,V>[] table;

    /**
     * Holds cached entrySet(). Note that AbstractMap fields are used
     * for keySet() and values().
     *  存儲具體元素的集合
     */
    transient Set<Map.Entry<K,V>> entrySet;

    /**
     * The number of key-value mappings contained in this map.
     *  map的元素個數(shù)
     */
    transient int size;

    /**
     * The number of times this HashMap has been structurally modified
     * Structural modifications are those that change the number of mappings in
     * the HashMap or otherwise modify its internal structure (e.g.,
     * rehash).  This field is used to make iterators on Collection-views of
     * the HashMap fail-fast.  (See ConcurrentModificationException).
     * 每次擴(kuò)容和更改map結(jié)構(gòu)的計數(shù)器
     */
    transient int modCount;

    /**
     * The next size value at which to resize (capacity * load factor).
     * 臨界值 當(dāng)實際大小(容量*填充因子)超過臨界值時,會進(jìn)行擴(kuò)容
     */
    int threshold;

    /**
     * The load factor for the hash table.
     * 加載因子
     */
    final float loadFactor;
3. 了解HashMap的構(gòu)造方法
  /**
     * 初始化map初始化的大小并制定加載因子的構(gòu)造方法
     * @param  initialCapacity 初始容量大小
     * @param  loadFactor      加載因子
     */
    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);
    }

    /**
     *
     * @param  initialCapacity 指定map的初始容量,默認(rèn)加載因子為0.75
     * @throws IllegalArgumentException if the initial capacity is negative.
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    /**
     * 默認(rèn)初始容量為16,加載因子為0.75
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    /**
     * 加載因子為0.75,指定一個map構(gòu)建一個初始化的map
     */
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }
4.Node節(jié)點類源碼:
 static class Node<K,V> implements Map.Entry<K,V> {
        // hash值
        final int hash;
        // key值
        final K key;
        // value 值
        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; }
        // 重寫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;
        }
        // 重寫equels方法
        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;
        }
    }

5.HashMap的put方法
 /**
     * 如果key存在,則value將替換原來的value值并返回被替換的那個值
     * @param key key值
     * @param value value值
     * @return  返回的值為,key下被替換的值
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

  /**
     * put key,value
     * @param hash key的hash值
     * @param key  key值
     * @param value value值
     * @param onlyIfAbsent 如果為true,key存在時value不予替換
     * @param evict if false, the table is in creation mode.
     * @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;
        // 檢驗table是否為空或者length為0,如果是則調(diào)用resize方法進(jìn)行初始化
        if ((tab = table) == null || (n = tab.length) == 0)
           // 數(shù)組擴(kuò)容
            n = (tab = resize()).length;
            // 計算key對應(yīng)的桶的位置是否存在存在元素,判斷為null表示不存在
        if ((p = tab[i = (n - 1) & hash]) == null)
            // 在table[i]出創(chuàng)建一個新節(jié)點
            tab[i] = newNode(hash, key, value, null);
        else { // table[i] 處已經(jīng)存在了元素(Hash碰撞)
            Node<K,V> e; K k;
            // 如果key值已經(jīng)存在,key不為null的情況下,e記錄下當(dāng)前key的node節(jié)點
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
              // 如果桶中的引用類型為 TreeNode,則調(diào)用紅黑樹的插入方法
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else { // 鏈表模式
                // 循環(huán)當(dāng)前鏈表
                for (int binCount = 0; ; ++binCount) {
                    //  p.next 為null,則將p.next指向先插入的node
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        // 如果鏈表長度大于設(shè)定閾值長度時(默認(rèn)為8),將鏈表轉(zhuǎn)換成紅黑樹
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        // 跳出循環(huán)
                        break;
                    }
                    // key存在,直接跳出循環(huán)進(jìn)行覆蓋操作
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // 表示key已經(jīng)存在
                V oldValue = e.value;
                // 如果允許替換,替換原值
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                  // 訪問后回調(diào)
                afterNodeAccess(e);
                // 返回舊值
                return oldValue;
            }
        }
        // modCount加1
        ++modCount;
        // size是否大于閾值,大于則進(jìn)行擴(kuò)容
        if (++size > threshold)
            resize();
         // 插入后回調(diào)
        afterNodeInsertion(evict);
        return null;
    }
6.擴(kuò)容機制

resize方法的執(zhí)行會伴隨hash的重新分配,并且會遍歷所有hash表中的元素,是非常耗時的,所以當(dāng)我們在編寫程序的時候盡量減少resize方法的執(zhí)行。

 /**
     * Initializes or doubles table size.  If null, allocates in
     * accord with initial capacity target held in field threshold.
     * Otherwise, because we are using power-of-two expansion, the
     * elements from each bin must either stay at same index, or move
     * with a power of two offset in the new table.
     *
     * @return the table
     */
    final Node<K,V>[] resize() {
       // 記錄原table數(shù)組
        Node<K,V>[] oldTab = table;
        // 計算oldCap的大小
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        // 擴(kuò)容臨界值(cap * loadFactor)
        int oldThr = threshold;
        int newCap, newThr = 0;
        // oldCap>0 表述map的buket數(shù)組已經(jīng)初始化
        if (oldCap > 0) {
             // 如果已經(jīng)達(dá)到容量最大值,不進(jìn)行擴(kuò)容(只能無情的進(jìn)行Hash碰撞了)
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            // 擴(kuò)容為原來的容量的2倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                // 左移一位(容量*2)
                newThr = oldThr << 1; // double threshold
        }
        // 若不滿足上面的oldCap > 0,表示數(shù)組還未初始化
        // 若當(dāng)前閾值不為0,則設(shè)置為當(dāng)前閾值
        // 這是因為HashMap有兩個帶參構(gòu)造器,可以指定初始容量,
        else if (oldThr > 0) 
            newCap = oldThr;
        else {       
            // 初始化為默認(rèn)的容量值      
            newCap = DEFAULT_INITIAL_CAPACITY;   
            // 容量界線 16* 0.75
            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"})
        // 擴(kuò)容后的數(shù)組大小
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        // 將老數(shù)組的數(shù)據(jù)重新復(fù)制與新數(shù)組中
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                // j位置存在數(shù)據(jù)
                if ((e = oldTab[j]) != null) {
                    // 清空數(shù)據(jù)
                    oldTab[j] = null;
                    // 若table數(shù)組的j位置只有一個節(jié)點,則直接將這個節(jié)點放入新數(shù)組,
                    // 使用 & 替代 % 計算出余數(shù),即下標(biāo)
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode) 
                         // 紅黑樹節(jié)點-執(zhí)行紅黑樹算法(hash沖突解決)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // 鏈表數(shù)據(jù)小于限制數(shù)據(jù)-執(zhí)行鏈表結(jié)構(gòu)
                        // 創(chuàng)建兩個頭尾節(jié)點,表示兩條鏈表,舊數(shù)據(jù)的一條鏈表可能被查分到兩條鏈表上
                        // // 一條下標(biāo)不變的鏈表,一條下標(biāo)+oldCap
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                             // e.hash & oldCap==0 原鏈表的索引值
                            if ((e.hash & oldCap) == 0) {
                                // 如果最后一個元素為null,說明為頭節(jié)點
                                if (loTail == null)
                                    // 設(shè)置頭結(jié)點為e
                                    loHead = e;
                                else // 頭節(jié)點已經(jīng)設(shè)置了元素,直接將該元素設(shè)置在尾節(jié)點的next
                                    loTail.next = e;
                                // 設(shè)置當(dāng)前尾節(jié)點為e
                                loTail = e;
                            }
                            // 若與原容量做與運算,結(jié)果為1,表示將這個節(jié)點放入到新數(shù)組中,下標(biāo)將改變
                            else { 
                                if (hiTail == null) // 尾節(jié)點為空,說明該鏈表還沒有值
                                    // 設(shè)置頭結(jié)點為e
                                    hiHead = e;
                                else
                                    // 頭節(jié)點已經(jīng)設(shè)置了元素,直接將該元素設(shè)置在尾節(jié)點的next
                                    hiTail.next = e;
                                // 設(shè)置當(dāng)前尾節(jié)點為e
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        // 所有節(jié)點遍歷完后,判斷下標(biāo)不變的鏈表是否有節(jié)點在其中
                        if (loTail != null) {
                            // 將這條鏈表的最后一個節(jié)點的next指向null
                            loTail.next = null;
                            // 將鏈表loHead放入新數(shù)組的相同位置
                            newTab[j] = loHead;
                        }
                        // 將變化后的元素生成的新鏈表放在新的計算位置
                        if (hiTail != null) {
                            hiTail.next = null;
                            // 這條鏈表放入的位置要在原來的基礎(chǔ)上加上oldCap
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        // 將新創(chuàng)建的map Tab 返回
        return newTab;
    }

注意: 這邊有一個算法公式num % 2^n == num & (2^n - 1),所以上述resize方法執(zhí)行的時候?qū)⑶笥噙\算轉(zhuǎn)化為位&運算。

5.HashMap的get方法
 // key獲取元素
 public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    /**
     * Implements Map.get and related methods.
     *
     * @param key的hash值
     * @param 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;
          //   1、HashMap中存儲數(shù)據(jù)的數(shù)組table不為null;
         //   2、數(shù)組table長度大于0
         //   3、table已經(jīng)創(chuàng)建,且通過hash值計算出的節(jié)點存放位置有節(jié)點存在;
        // 若上面三個條件都滿足,才表示HashMap中可能有我們需要獲取的元素
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
             // 定位到元素在數(shù)組中的位置后,我們開始沿著這個位置的鏈表或者樹開始遍歷尋找
            // 注:JDK1.8之前,HashMap的實現(xiàn)是數(shù)組+鏈表,到1.8開始變成數(shù)組+鏈表+紅黑樹
            // 首先判斷這個位置的第一個節(jié)點的key值是否與參數(shù)的key值相等,
            // 若相等,則這個節(jié)點就是我們要找的節(jié)點,將其返回
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
           // 遍歷鏈表數(shù)據(jù)
            if ((e = first.next) != null) {
                // 如果節(jié)點為紅黑樹結(jié)構(gòu),遍歷數(shù)結(jié)構(gòu)查詢
                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);
            }
        }
        // 未查詢到,返回null
        return null;
    }
在這里插入圖片描述
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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