java 8 HashMap 源碼閱讀

閱讀java源碼可能是每一個(gè)java程序員的必修課,只有知其所以然,才能更好的使用java,寫出更優(yōu)美的程序,閱讀java源碼也為我們后面閱讀java框架的源碼打下了基礎(chǔ)。閱讀源代碼其實(shí)就像再看一篇長(zhǎng)篇推理小說一樣,不能急于求成,需要慢慢品味才行。這一系列的文章,記錄了我閱讀源碼的收獲與思路,讀者也可以借鑒一下,也僅僅是借鑒,問渠那得清如許,絕知此事要躬行!要想真正的成為大神,還是需要自己親身去閱讀源碼而不是看幾篇分析源碼的博客就可以的。

正文

HashMap是我們經(jīng)常用的的一個(gè)集合類,其中java對(duì)于Hash散列表的維護(hù)、大小的動(dòng)態(tài)擴(kuò)展以及解決Hash沖突的方法都是值得我們借鑒的。如何更好地使用HashMap,建議大家把JAVA API文檔拿來讀讀,其中對(duì)于如何很好的使用HashMap做了詳細(xì)的說明,在一個(gè)是將HashMap的源代碼自行分析一遍。

總結(jié)

JAVA8中對(duì)HashMap的優(yōu)化

通過閱讀源碼,我們可以了解到,在java1.8這個(gè)版本中,SUN大神們?yōu)閔ashmap的查詢進(jìn)行了進(jìn)一步優(yōu)化,原來hashmap是hash表+鏈表的形式,在1.8中變?yōu)榱薶ash表+鏈表/樹的形式,即在一定條件下同一hash值對(duì)應(yīng)的鏈表會(huì)被轉(zhuǎn)化為樹,進(jìn)而優(yōu)化了查詢。通過這次學(xué)習(xí)Hashmap的源碼實(shí)現(xiàn),我們可以學(xué)習(xí)到如何利用樹來對(duì)數(shù)組查找進(jìn)行優(yōu)化。那么何時(shí)樹化?何時(shí)調(diào)整表的大小?
在HashMap的類成員中,有一個(gè)叫做MIN_TREEIFY_CAPACITY的常量,它規(guī)定了當(dāng)HashMap被使用的空間大小超過這個(gè)常量的值時(shí),才會(huì)開始樹化。而針對(duì)每一個(gè)hash值對(duì)應(yīng)的鏈表,有一個(gè)叫TREEIFY_THRESHOLD
常量,規(guī)定了當(dāng)鏈表的大小超過其時(shí),就對(duì)此鏈表進(jìn)行樹化。

源碼分析

HashMap關(guān)鍵的變量:

/**
     * The default initial capacity - MUST be a power of two.
     *
     *   HashMap中哈希表的初始容量默認(rèn)值
     */
    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.
     *
     * 哈希表的最大容量
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * The load factor used when none specified in constructor.
     *
     * 負(fù)載因子的默認(rèn)值
     */
    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)鏈表存儲(chǔ)量達(dá)到多大時(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.
     *
     * 將樹轉(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.
     *
     * 這個(gè)字段決定了當(dāng)hash表的至少大小為多少時(shí),鏈表才能進(jìn)行樹化。這個(gè)設(shè)計(jì)時(shí)合理的,
     * 因?yàn)楫?dāng)hash表的大小很小時(shí),這時(shí)候表所需的空間還不多,可以犧牲空間減少時(shí)間,所以這個(gè)情況下
     * 當(dāng)存儲(chǔ)的節(jié)點(diǎn)過多時(shí),最好的辦法是調(diào)整表的大小,使其增大,而不是將鏈表樹化。
     * 
     */
    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.)
     *
     * hash表
     */
    transient Node<K,V>[] table;

    /**
     * The number of key-value mappings contained in this map.
     *  Hashmap當(dāng)前的大小
     */
    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).
     * 
     */
    transient int modCount;

    /**
     * The next size value at which to resize (capacity * load factor).
     *
     * @serial
     */
    // (The javadoc description is true upon serialization.
    // Additionally, if the table array has not been allocated, this
    // field holds the initial array capacity, or zero signifying
    // DEFAULT_INITIAL_CAPACITY.)
    //閥值,它決定了hashmap何時(shí)進(jìn)行擴(kuò)容。
    int threshold;

    /**
     * The load factor for the hash table.
     *  負(fù)載因子,用于計(jì)算閥值,它等于threshold與hashmap當(dāng)前容量的比例。
     * @serial
     */
    final float loadFactor;

再介紹了hashmap的重要變量之后,我們就可以看看其最關(guān)鍵的put()方法與resize()方法了:
put():

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

    /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing 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;
        
        //如果還沒有為hash表申請(qǐng)空間,那么就使用resize()方法初始化hash表。
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //如果沒有發(fā)生hash沖突,則直接將數(shù)據(jù)存入hash表中
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        //如果發(fā)生了沖突
        else {
            Node<K,V> e; K k;
            //判斷是否與鏈表頭結(jié)點(diǎn)相同
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //判斷當(dāng)前要插入的鏈表表示的結(jié)構(gòu)是否是樹,如果是則交給putTreeVal()處理
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);

           //當(dāng)要插入的數(shù)據(jù)不是頭結(jié)點(diǎn),并且鏈表沒有被樹化的情況下
            else {
                //遍歷鏈表,判斷是做修改還是插入操作
                for (int binCount = 0; ; ++binCount) {
                    //如果是插入操作
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        //判斷是否達(dá)到樹化的標(biāo)準(zhǔn)
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);         //樹化鏈表
                        break;
                    }
                    //發(fā)現(xiàn)當(dāng)前鏈表中的結(jié)點(diǎn)有與要插入的數(shù)據(jù)相同的key,跳出循環(huán)進(jìn)行修改操作
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //修改操作,,進(jìn)行Value數(shù)據(jù)的修改
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                //此方法是在LinkedHashMap中實(shí)現(xiàn)的,在HashMap中為空
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        //判斷put()后是否需要擴(kuò)容
        if (++size > threshold)
            resize();
         //此方法是在LinkedHashMap中實(shí)現(xiàn)的,在HashMap中為空
        afterNodeInsertion(evict);
        return null;
    }

這里需要注意幾點(diǎn):
1.為什么在查找插入數(shù)據(jù)在hash表中相應(yīng)位置時(shí),使用的是hash(key)&(length-1)而不是hash(key)?
因?yàn)閔ash(key)的值是隨機(jī)的,無法確定其范圍,通過&操作,相當(dāng)于對(duì)hash表的長(zhǎng)度取模,能夠在保證數(shù)據(jù)隨機(jī)均勻的分布在hash表中,并且限制hash值的范圍。

2.因?yàn)殒湵淼拇嬖冢岳碚撋蟞ashmap的容量是沒有上限的,但是當(dāng)hash表無法繼續(xù)擴(kuò)充時(shí),隨著存儲(chǔ)數(shù)據(jù)的增加,其查找效率會(huì)逐漸降低。
3.負(fù)載因子的作用:負(fù)載因子,其實(shí)表達(dá)的都是HashMap容量空間的占有程度,它存在的意義是為了協(xié)調(diào)查找效率與空間利用率之間的平衡。Capacity*loadFactor=threshold,threshold其實(shí)就表示了hashmap的真實(shí)容量大小,而Capacity則是hash表的長(zhǎng)度。負(fù)載因子越大則代表容量空間的占有程度高,也就是能容納更多的元素,元素多了,鏈表大了,所以此時(shí)查找效率就會(huì)降低。反之,負(fù)載因子越小則鏈表中的數(shù)據(jù)量就越稀疏,此時(shí)會(huì)對(duì)空間造成爛費(fèi),但是此時(shí)查找效率高。

resize():

 final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        //先確定新表的hash表長(zhǎng)度與閥值。
        if (oldCap > 0) {
            //判斷當(dāng)前hash表的長(zhǎng)度是否已經(jīng)達(dá)到上限,如果是則將閥值設(shè)置為Integer.MAX_VALUE并返回
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //將容量大小增加為原來的二倍,并計(jì)算相應(yīng)的閥值
            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"})
          //在確定hash表長(zhǎng)度后,創(chuàng)建新表,將舊表中的數(shù)據(jù)進(jìn)行遷移到新表。
            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;
                    //判斷是否已經(jīng)樹化,如果是則調(diào)用樹化的相應(yīng)方法進(jìn)行數(shù)據(jù)遷移
                    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;

                        //這里的代碼需要好好看,就是因?yàn)榇颂帉?shí)現(xiàn)方式的原因,
                       //導(dǎo)致了hashmap遍歷時(shí)不能保證數(shù)據(jù)能夠一直按照插入或者修改的順序訪問。
                        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;
    }

關(guān)于resize需要注意的是:
1.resize擴(kuò)容后的容量是原來的兩倍,直到容量達(dá)到最大,這時(shí)就會(huì)更改閾值來繼續(xù)擴(kuò)容。
2.正是因?yàn)閞esize的擴(kuò)容原理,導(dǎo)致了Hashmap不能保證插入數(shù)據(jù)的順序性,當(dāng)然如果一定要保證,我們可以使用LinkedHashMap

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

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

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