1. 程式人生 > >認識Java8中HashMap原理

認識Java8中HashMap原理

HashMap繼承和實現

由原始碼可以看出來HashMap繼承AbstractMap抽象類,並實現了Map、Cloneable、Serializable介面,而AbstractMap抽象類實現了Map介面。

結構組成

在JDK7版本中HashMap是由陣列+連結串列組成的,而在JDK8中HashMap是由陣列+連結串列+紅黑樹實現的,對於原因在後面會講到,如圖所示;

注:圖來源於美團點評技術團隊

HashMap類的屬性

Node[] table陣列:通俗講就是雜湊桶,table的大小必須是2的n次方,預設長度時16。

size:實際存在的鍵值對的數量;

modCount:主要用來記錄HashMap內部結構發生變化的次數,主要用於迭代的快速失敗。

threshold:鍵值對閾值,也就是容納鍵值對的最大數量;

loadFactor:負載因子,預設值時0.75,建議不要隨便修改。

這其中的關係是:threshold = table.length * loadFactor。

儲存原理

通過原始碼可以看到Node[] table陣列是個很重要的屬性,看原始碼:

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;//key的雜湊值,資料儲存的位置
        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;
        }
    }

Node 是一個內部類,本質就是一個鍵值對。

資料是如何儲存的?

當存入這樣的資料時,map.put("東牆","我是東牆")時,系統會呼叫“東牆”這個key的hashCode()方法來計算這個key的hash值,然後在通過hash演算法的後兩步運算來獲得儲存的位置,有時不同的key會計算出相同的索引值,也就是會定位到相同的位置,這時候會發生雜湊碰撞。所以當table的長度越大時,碰撞的機率就越小,但要考慮效能的問題,所以就需要好的雜湊演算法和擴容機制。在這裡使用鏈地址法來解決雜湊碰撞的問題。當索引值相同時,後來的資料會鏈在之前的資料之後。

索引的位置的計算方式

在原始碼中,有這幾行程式碼可以看到怎麼計算的索引值的:

static final int hash(Object key) { 
     int h;
     // h = key.hashCode() 為第一步 取hashCode值
     // h ^ (h >>> 16)  為第二步 高位參與運算
     return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

總結下來就是,取key值hasCode值、高位運算、取模運算。在這裡使用(n-1)& h來計算模值(h%length)是非常好的,提高了速度,因為&的效能比%的要快,演算法舉例說明:


HashMap的put()方法是如何工作的?

這裡借鑑其他人的圖解:


我們可以看原始碼來進行解讀:

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);//對key進行計算雜湊值
}
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)//1.table為空時,呼叫resize()方法進行擴容
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)//2.計算索引值,並判斷此位置上是否有資料
            tab[i] = newNode(hash, key, value, null);//3.沒有則新增此資料
        else {//4.此位置上有資料
            Node<K,V> e; K k;
            if (p.hash == hash &&//5.判斷key是否存在,存在則直接覆蓋
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)//6.判斷鏈是否時紅黑樹
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {//7.鏈為連結串列
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);//8.將此資料鏈接在前一個數據之後
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);//連結串列長度大於8則轉換為紅黑樹
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;//key已經存在,則直接覆蓋
                }
            }
            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;
    }

為什麼要加入紅黑樹?

即使負載因子和Hash演算法設計的再合理,也會出現連結串列過於長,會影響效能,所以當鏈長度大於8時,會轉換為紅黑樹,紅黑樹結合了陣列和連結串列的有點,易查詢和易修改。

HashMap的擴容機制

我們還是結合原始碼來進行分析

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) {//最大容量為2^30
                threshold = Integer.MAX_VALUE;//當為最大容量時,不再擴容,為int的最大值2^31-1
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)//容量大於16小於最大值時容量擴大2倍
                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 = 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;
                    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;
                        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;
    }