JAva 8 HashMapソース読み

11494 ワード

シーケンス
Javaソースコードを読むのはjavaプログラマー一人一人の必修科目かもしれませんが、それを知ってこそ、javaをよりよく使用することができ、より美しいプログラムを書くことができます.javaソースコードを読むのも、javaフレームワークのソースコードを読むための基礎を築きました.ソースコードを読むのは、実はもう一つの長編推理小説を読むように、成功を急ぐのではなく、ゆっくり味わう必要があります.この一連の文章は、私がソースコードを読む収穫と構想を記録して、読者も参考にすることができて、ただ参考にすることができて、渠那を聞いてこのようにして、このことを絶対に知っています!本当に大神になるには、ソースを分析するブログをいくつか読むのではなく、自分でソースを読む必要があります.
本文
HashMapは、JavaがHashハッシュ・リストのメンテナンス、サイズの動的拡張、およびHash競合を解決する方法について参考になる集合クラスです.HashMapの使用方法については、JAVA APIドキュメントを読むことをお勧めします.HashMapの使用方法について詳しく説明します.HashMapのソースコードを自分で分析します.
まとめ
JAVA 8におけるHashMapの最適化
ソースコードを読むことで、java 1.8というバージョンでは、SUN大神たちがhashmapのクエリーをさらに最適化していることがわかります.元のhashmapはhashテーブル+チェーンテーブルの形式で、1.8ではhashテーブル+チェーンテーブル/ツリーの形式になります.つまり、一定の条件で同じhash値に対応するチェーンテーブルがツリーに変換され、クエリーが最適化されます.今回Hashmapのソース実装を学習することで,ツリーを用いて配列検索を最適化する方法を学ぶことができる.では、いつ木化しますか.テーブルのサイズはいつ変更しますか?HashMapというクラスメンバーの中にMIN_TREEIFY_CAPACITYの定数は、HashMapが使用される空間サイズがこの定数の値を超えると、ツリー化が開始されることを規定しています.hash値に対応するチェーンテーブルごとにTREEIFY_というものがありますTHRESHOLD定数は,チェーンテーブルの大きさがそれを超えると,このチェーンテーブルをツリー化することを規定している.
ソース分析
HashMapキー変数:
/**
     * The default initial capacity - MUST be a power of two.
     *
     *   HashMap            
     */
    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.
     *
     *         
     */
    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.
     *
     *         ,            ,      
     */
    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.
     *
     *           。
     */
    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.
     *
     *         hash          ,        。        ,
     *    hash       ,            ,          ,       
     *          ,            ,    ,        。
     * 
     */
    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[] table;

    /**
     * The number of key-value mappings contained in this map.
     *  Hashmap     
     */
    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      。
    int threshold;

    /**
     * The load factor for the hash table.
     *      ,      ,   threshold hashmap       。
     * @serial
     */
    final float loadFactor;

hashmapの重要な変数を紹介した後、最も重要な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[] tab; Node p; int n, i;
        
        //      hash     ,     resize()     hash 。
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //      hash  ,        hash  
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        //       
        else {
            Node e; K k;
            //            
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //                   ,      putTreeVal()  
            else if (p instanceof TreeNode)
                e = ((TreeNode)p).putTreeVal(this, tab, hash, key, value);

           //            ,             
            else {
                //    ,            
                for (int binCount = 0; ; ++binCount) {
                    //       
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        //           
                        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;
                }
            }
            //    ,,  Value     
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                //     LinkedHashMap    , HashMap   
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        //  put()       
        if (++size > threshold)
            resize();
         //     LinkedHashMap    , HashMap   
        afterNodeInsertion(evict);
        return null;
    }

ここで注意すべき点は、1.なぜhashテーブルに挿入されたデータの対応する位置を検索する際にhash(key)&(length-1)をhash(key)ではなくhash(key)を使用するのか.hash(key)の値はランダムであるため、その範囲を特定することができず、&操作によりhashテーブルの長さを型取ることに相当し、データがhashテーブルにランダムに均一に分布することを保証し、hash値の範囲を制限することができる.2.チェーンテーブルが存在するため、理論的にはhashmapの容量に上限はないが、hashテーブルが拡張を継続できない場合、記憶データの増加に伴い、その検索効率は徐々に低下する.3.負荷因子の役割:負荷因子は、HashMap容量空間の占有度を表し、検索効率と空間利用率のバランスをとるために存在する.Capacity*loadFactor=threshold、thresholdはhashmapの実際の容量サイズを表し、Capacityはhashテーブルの長さです.負荷因子が大きいほど容量空間の占有度が高く、すなわちより多くの要素を収容でき、要素が多くなり、チェーンテーブルが大きくなるため、検索効率が低下する.逆に,負荷因子が小さいほどチェーンテーブル中のデータ量がまばらになり,空間に悪影響を及ぼすが,この場合検索効率が高い.
resize():
 final Node[] resize() {
        Node[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        //      hash      。
        if (oldCap > 0) {
            //    hash            ,          Integer.MAX_VALUE   
            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"})
          //   hash    ,    ,              。
            Node[] newTab = (Node[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node 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)e).split(this, newTab, j, oldCap);
                    //        
                    else { // preserve order
                        Node loHead = null, loTail = null;
                        Node hiHead = null, hiTail = null;
                        Node next;

                        //          ,             ,
                       //   hashmap                          。
                        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;
    }

resizeについて注意しなければならないのは、1.resize拡張後の容量は、容量が最大になるまで2倍になり、閾値が変更されて拡張が継続されることです.2.resizeの拡張原理によって、Hashmapはデータ挿入の順序性を保証できない.もちろん、保証しなければならないならLinkedHashMapを使うことができる.