1. 程式人生 > >HashMap原始碼分析(基於1.8)

HashMap原始碼分析(基於1.8)

HashMap1.7和1.8變動比較多。
關於HashMap 1.7的版本,倪升武的部落格總結的很好。

這裡我主要來介紹一下1.8中的HashMap。由於HashMap原始碼太長,我只挑選了部分進行分析,如果有沒有分析到的重點難點或者大家有疑問的地方,希望大傢俬信給我,大家共同進步~

HashMap的儲存思想演化

在1.7中,HashMap是以“陣列+連結串列”的基本結構來儲存key和value構成的Entry單元的。其中連結串列結構的存在是用來處理hash碰撞的。這種結構有它的優點,比如容易實現等。但是我們可以設想這樣一種情況,如果說有成百上千個節點在hash時發生碰撞,儲存一個連結串列中,那麼如果要查詢其中一個節點,那將不可避免的花費o

n的時間複雜度來進行查詢。基於這點,1.8中將HashMap的基本結構進行了改善,其中hashMap的基本結構依然是“陣列+連結串列”,但是當hash碰撞太多以至於連結串列過長的時候,連結串列結構將演化成樹(具體來說應該是紅黑樹)的結構。我們都知道,紅黑樹是二叉查詢樹平衡形式的一種,因此查詢效能較連結串列來說,有了很大提升。
其次,在1.7中,是使用Entry這個類作為基本儲存單元的,在1.8中,可能為了配合紅黑樹的使用,改進成了Node這個類,當然,差不多隻是名字變了而已,類內部實現的形式差別不是很大。

原始碼分析

前言

原始碼中的很多備註寫的非常好,這裡挑出幾個與大家一起學習:

package java.util;

/**
 * Hash table based implementation of the <tt>Map</tt> interface.  This
 * implementation provides all of the optional map operations, and permits
 * <tt>null</tt> values and the <tt>null</tt> key.  (The <tt>HashMap</tt>
 * class
is roughly equivalent to <tt>Hashtable</tt>, except that it is * unsynchronized and permits nulls.) This class makes no guarantees as to * the order of the map; in particular, it does not guarantee that the order * will remain constant over time. * HashMap是一個實現Map介面的雜湊表,並且實現了map集合的所有操作,允許key和value為null * 除了執行緒安全性和null設定方面的不同,HashMap和HashTable大致是相同的。這個類 * 不保證map中的順序。尤其是,它也不能保證順序的恆久不變。 * <p>This implementation provides constant-time performance for the basic * operations (<tt>get</tt> and <tt>put</tt>), assuming the hash function * disperses the elements properly among the buckets. Iteration over * collection views requires time proportional to the "capacity" of the * <tt>HashMap</tt> instance (the number of buckets) plus its size (the number * of key-value mappings). Thus, it's very important not to set the initial * capacity too high (or the load factor too low) if iteration performance is * important. * 只要hash演算法能夠將資料雜湊的足夠好,那麼getput這種基本操作的用時是固定的。 * 而集合檢視的遍歷需要的時間與HashMap例項的大小是成比例的。因此,如果遍歷操作 * 非常重要的話,不要講初始容量設定太大(或者將負載因子設定太低)是很重要的 */

上面是關於HashMap類原始碼中的幾點說明,本人語言表達能力比較差,以上可能有些翻譯的不是很好,大家湊合看吧。

1.HashMap中的幾個成員變數
    private static final long serialVersionUID = 362498820763181265L;

    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16,最小容量:16

    static final int MAXIMUM_CAPACITY = 1 << 30;//HashMap的最大容量

    /**
     * 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.
     */
     //下面這個值的意義是:位桶(bin)處的資料要採用紅黑樹結構進行儲存時,整個Table的最小容量
    static final int MIN_TREEIFY_CAPACITY = 64;

    //分配的時候,table的長度總是2的冪
    transient Node<K,V>[] table;
    transient Set<Map.Entry<K,V>> entrySet;
    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;
    //門限閥值,計算方法:容量*負載因子
    int threshold;
2.幾個比較重要的方法

下面我先挑幾個比較重要又難以理解的方法原始碼來說一下:

     //返回根據給定的目標容量所計算出來的最接近的2的冪,這有利於改善hash演算法
    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;
    }

get()方法:

    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;

        //這裡可以解釋一下為什麼要求table的長度為2的冪
        //n為2的冪,那麼化成二進位制就是100...00,減一之後成為0111..11
        //對於小於n-1的hash值,索引位置就是hash,大於n-1的就是取模,這樣在indexFor()方法裡可以提高&運算的速度
        //且最後一位為1,這樣保證雜湊的均勻性

        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {        
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                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);
            }
        }
        return null;
    }

插入操作:

    //進行插入操作,分為三種情況,1.插入位置無資料,直接存入 2.插入位置有資料,但是較少且符合連結串列結構儲存的條件,那麼以連結串列操作存入
    //3.插入位置有資料,但是以樹結構進行儲存,那麼以樹的相關操作進行存入
    //較1.7的put相比,複雜了很多,不過卻換取了查詢時的效能提升。
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)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;
                    }
                    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;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

resize()操作:

    /**
     * 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
     */
    /**
     *初始化或者將size擴至2倍大小。如果滿了,就分配符合初始容量目標下的門閥值
     *否則,因為我們是進行2的冪的擴充套件操作,每個位桶處的資料要麼呆在相同的索引處,要麼移動
     *處,要麼移動2的冪的位移量。
     */
    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;//超過1>>30大小,無法擴容只能改變 閾值
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold     //門限值*2
        }
        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"})
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];//table在這裡產生了。
        table = newTab;//下面對原table中已儲存的資料進行遷移,分樹和連結串列2種情況處理
        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;//將單節點移動到新位置
                    else if (e instanceof TreeNode)         //下面是分開2種情況操作,一種是發生碰撞的節點以樹結構進行儲存,另一種是以連結串列結構儲存
                        ((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) {//根據hash值與oldCap的運算結果,將連結串列中集結的元素分開
                                if (loTail == null)     //運算結果為0的元素,用lo記錄並連線成新的連結串列
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {                      //運算結果不為0的資料,
                                if (hiTail == null)         //用li記錄
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead; //lo仍然放在“原處”,這個“原處”是根據新的hash值算出來的。
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;//li放在j+oldCap位置
                        }
                    }
                }
            }
        }
        return newTab;
    }

樹化操作:

    //對連結串列進行樹結構的轉化儲存
    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;
            do {
                TreeNode<K,V> p = replacementTreeNode(e, null);
                if (tl == null)
                    hd = p;
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);
            if ((tab[index] = hd) != null)
                hd.treeify(tab);
        }
    }

值得一提的是,在1.8的HashMap中新添了一個內部靜態類TreeNode,該類繼承了LinkedHashMap.Entry。

1.8的HashMap原始碼較多,一共有2380行,這裡我挑選了幾個比較重要的來說了一下,其餘的並不是很難理解。
小總結:

  • 1.8中的HashMap基本實現結構是“陣列+連結串列”,不過當連結串列過長時(連結串列長度超過8),會演化成紅黑樹。
  • 原始碼要求HashMap底層實現陣列的長度為2的冪,原因是可以得到較好的雜湊效能。
  • 在HashMap進行擴容時,會進行2倍擴容,而且會將雜湊碰撞處的資料再次分散開來,一部分依照新的hash索引值呆在“原處”,一部分加上偏移量移動到新的地方。