1. 程式人生 > >Map之HashMap原始碼實現

Map之HashMap原始碼實現

一、引言

1.導語

在此之前學習HashMap之前,我們首先對先前學習的List進行總結一些:

型別 說明
ArrayList 底層是陣列,順序插入。查詢快、增刪慢
LinkedList 底層是連結串列,順序插入。查詢慢、增刪塊

但是這樣的集合我們還是不滿意啊,有沒有查詢塊,增刪也快的集合,那 就是我們今天要學習的HashMap。

2.要點

要點 說明
是否可以為空 key和value都可以為空,但是key只能一個為空,value則不限
是否有序 無序
是否可以重複 key重複會覆蓋,value則可以重複
是否執行緒安全 非執行緒安全

二、分析

1.繼承關係圖

在這裡插入圖片描述

2.欄位

   /**
     * The default initial capacity - MUST be a power of two.
     * 預設的容量
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * 最大容量上限
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

   /**
     * 負載因子,調控控制元件與衝突率的因數
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

   /**
     * 連結串列轉換為樹的閾值,超過這個長度的連結串列會被轉換為紅黑樹
     */
    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.
     * 當進行resize操作時,小於這個長度的樹會被轉換為連結串列
     */
    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.
     * 連結串列被轉換成樹形的最小容量,如果沒有達到這個容量只會執行resize進行擴容
     */
    static final int MIN_TREEIFY_CAPACITY = 64;

    /**
     * 儲存元素的實體陣列
     */
    transient Node<K,V>[] table;

    /**
     * Holds cached entrySet(). Note that AbstractMap fields are used
     * for keySet() and values().
     * set陣列,用於迭代元素
     */
    transient Set<Map.Entry<K,V>> entrySet;

    /**
     * 存放元素的個數,但不等於陣列的長度
     */
    transient int size;

    /**
     * 修改的次數
     */
    transient int modCount;

    /**
     * The next size value at which to resize (capacity * load factor).
     *
     * 臨界值  如果實際大小超過臨界值,就會進行擴容。threshold=載入因子 * 容量
     */
    int threshold;

    /**
     * 載入因子
     *
     * @serial
     */
    final float loadFactor;

2.構造方法

    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and load factor.
     *
     * @param  initialCapacity the initial capacity
     * @param  loadFactor      the load factor
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive
     *  引數為:初始化大小和負載因子
     */
    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);
    }

    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and the default load factor (0.75).
     *
     * @param  initialCapacity the initial capacity.
     * @throws IllegalArgumentException if the initial capacity is negative.
     * 引數為初始化大小
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     * 預設無參構造方法
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    /**
     * Constructs a new <tt>HashMap</tt> with the same mappings as the
     * specified <tt>Map</tt>.  The <tt>HashMap</tt> is created with
     * default load factor (0.75) and an initial capacity sufficient to
     * hold the mappings in the specified <tt>Map</tt>.
     *
     * @param   m the map whose mappings are to be placed in this map
     * @throws  NullPointerException if the specified map is null
     * 引數為集合
     */
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

3.HashMap的實現原理

3.1圖示

在這裡插入圖片描述

3.2分析

  • 連結串列的實現如下
    /**
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
     * 相比LinkedList的雙向列表,Node是一個單向列表,通過next來實現
     */
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        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; }

        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;
        }
    }
  • 紅黑樹的實現(待補充(後面會有一篇專門的文章研究)):
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);
        }
}

4.方法

4.1 儲存:put(K key, V value)方法

	// 需要放入的鍵與值
    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  鍵值的hash值
     * @param key the key         鍵值
     * @param value the value to put   值 
     * @param onlyIfAbsent if true, don't change existing value   如果為true,如果放入已存在key,value則不會覆蓋
     * @param evict if false, the table is in creation mode.  如果是false,table陣列是建立模式,這裡用不到,hash值才能用到。
     * @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陣列為空或長度為0,則對其進行初始化,分配記憶體空間
        if ((tab = table) == null || (n = tab.length) == 0) 
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
        	// 當put的key在陣列中不存在時,直接new一個Node元素放入
            tab[i] = newNode(hash, key, value, null);
        else {
           // 此種情況是key元素在集合中已存在的情況
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k)))) // 如果tab[(n - 1) & hash]位置的第一個元素的key和要儲存的key相等,則將p的值賦值給e,在後面進行替換
                e = p;
            else if (p instanceof TreeNode)  // 如果是紅黑樹節點,則呼叫其put方法
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {  // table[[(n - 1) & hash]第一個節點不符合要求,則迴圈其中的每一個元素
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) { // 此處主要是為了防止hash碰撞,則put的key在此連結串列不存在
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st 如果連結串列的長度超過8,則進行紅黑樹進行轉換。1,8後追加:連結串列查詢的複雜度是O(n),而紅黑樹是O(log(n)),但是如果hash結果不均勻會極大的影響效能
                            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(); // 如果size大於擴容閥值,則進行擴容操作
        afterNodeInsertion(evict);
        return null;
    }

4.2擴容: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;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) { // 如果目前table的容量大於最大容量的上限,則不會進行擴容
                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和newThr進行賦值
            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 = newTab;
         // 擴容完畢,需要把原來的元素逐一拷貝到新的集合中去
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    //將原來的置為 null,方便垃圾回收器進行回收
                    oldTab[j] = null; 
                    // 如果e.next為null,表示此連結串列是單節點,直接根據e.hash & (newCap - 1)得到新的位置進行賦值即可
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                    	 // 如果是紅黑樹節點,則呼叫紅黑樹的方法
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                    	// 此分支是:連結串列的複製
                    	// 而且其元素在陣列中位置確定的方式:
                    	// 不是根據hash演算法生成新的位置,而是採用了原始位置+原始長度得到新的位置
                        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) {
                            	// 將符合條件的元素進行新的連結串列拼接 
                                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) {
                        	// 將連結串列的尾部的next置為空
                            loTail.next = null;
                            newTab[j] = loHead; 
                        }
                        if (hiTail != null) {
                        	// 將連結串列的尾部的next置為空
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

4.3獲取:get(Object key)

   public V get(Object key) {
        Node<K,V> e;
        // 可以看出主幹方法在getNode(key)裡面
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        // 通過key的hash定位到桶的位置,並且第一個元素不是null
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            // 總是檢查第一個節點
            // 如果第一個節點的hash值且key值也相等,直接返回first元素 
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
            	// 判斷next節點是不是紅黑樹節點,如果是直接呼叫其getTreeNode方法得到其treeNode節點
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                // 進行迴圈,去除符合條件的Node節點。迴圈的結束的條件是:直到連結串列的尾部
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

4.4 Map集合複製:putMapEntries(Map<? extends K, ? extends V> m, boolean evict)

    public HashMap(Map<? extends K, ? extends V> m) {
    	// 負載因子初始化
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        // 真正進行map複製的方法
        putMapEntries(m, false);
    }

    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        // 傳入的map不為空的情況下進行復制操作
        if (s > 0) {
        	// table未初始化,s為傳入集合的元素個數
            if (table == null) { // pre-size
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                // 如果t大於閾值,則初始化閥值
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            // 已經初始化,但元素數大於閥門,需要進行擴容操作
            else if (s > threshold)
                resize();
            // 迴圈遍歷,複製資料
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }

4.5 其他1:hash(Object key)

    static final int hash(Object key) {
        int h;
        // 通過hashCode()的高16位異或低16位實現:
        // 速度、功效、質量來考慮的,這麼做可以在陣列table的length比較小的時候,也能保證     	考慮到高低Bit都參與到Hash的計算中,同時不會有太大的開銷
        // 參考:https://blog.csdn.net/login_sonata/article/details/76598675 部分內容
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

4.6 其他2:tableSizeFor(int cap)

	// 作用:返回給定引數的最小二次冪的值.
	// 我們知道,HashMap的capacity的值必須是2的次冪;
    static final int tableSizeFor(int cap) {
    	// 先看一個規律:
    	// 7 = 0111,其最小2^次冪為1000 = 0111+1
    	// 11=1011,其最小2^次冪為10000 = 01111+1
    	// 29 = 011101,其最效2^次冪為100000 = 011111+1
    	// 由此我們得到:對於給定的整數cap,其二進位制第一次出現1的位數為n,那麼氣最小的二次冪的值為:2^(n + 1) 或 2^n
		
		// 看這個方法的程式碼如下:
		// n |= n >>> 1 是為了確保第一個1及其其後1位都是1
		//  n |= n >>> 2 是為了確保第一個1及其其後3位都是1
		//  n |= n >>> 4 是為了確保第一個1及其其後7位都是1
		//  n |= n >>> 8 是為了確保第一個1及其其後15位都是1
		//  n |= n >>>16 是為了確保第一個1及其其後所有位都是1
		// 所以大於cap的最小的2次冪就是(n + 1).
        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;
    }

三、結語

3.1回顧

回顧下上面的儲存、擴容、獲取等關鍵程式碼實現,再結合學習的四個要點,去對比理解其中的設計原理。

3.2思考

  • HashMap的是怎麼保證新增的元素的索引的(也就是說雜湊桶是如何分佈的)?
  • HshMap的擴容的流程是怎麼樣的?
  • 1.8比1.7版本在HashMap的那些方面做了改動和優化?
  • HashMap的hash演算法是怎麼實現的?為什麼要這麼實現?

3.3 關於紅黑樹理解在這裡:待完善