JDK1.8原始碼分析筆記-HashMap

袁志健發表於2019-03-03

PUT方法背後的原理

如何儲存

image

1. 計算出key的hash值

static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
複製程式碼

擾動處理混合雜湊碼的高位和低位(實際上只擾動了低位)。經過擾動處理,使得儲存Node的陣列長度在很小的時候(即取的低位很少時)減少衝突。

2. 計算出儲存位置 i

i = (n - 1) & hash
複製程式碼

其中n為陣列長度預設為16見HashMap類的常量定義

/**
 * The default initial capacity - MUST be a power of two.
 */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
複製程式碼

一般我們常見的固定範圍均勻分散用%(模運算),這邊使用&(與運算)是因為與運算具有更好的效能。

通過測試發現&操作在對0~100的資料分散到15個位置時並不能很好的均勻分佈,但是在分散到16個位置時就沒有問題。這是因為16的二進位制資料為10000 低位全是0,減1後為1111,這時&運算等價於%模運算。這就是很多面試題中提到的為什麼HashMap的陣列長度必須是2的n次冪的原因。

3. 建立Node物件並儲存到陣列中

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
    ...
    
    if ((p = tab[i = (n - 1) & hash]) == null)
                tab[i] = newNode(hash, key, value, null);
                
    ...
            
}


Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {
    return new Node<>(hash, key, value, next);
}
複製程式碼

不同的key計算出相同的儲存位置怎麼辦

image

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

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        // 1. 初始化table陣列
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        // 2. 根據key的hash值計算出Node存放在陣列中的位置,如果為null則直接儲存    
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            // 3. 即將放入的key與之前儲存的key一致
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            // 4. 之前儲存的Node已經升級為紅黑數結構    
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                // 5. 遍歷連結串列不存在則新增,長度>=8時連結串列轉換成紅黑樹
                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;
                }
            }
            // 6. 存在則替換就的value
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        // 7. 長度大於閥值進行擴容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
複製程式碼

總結:

  • key的引用地址相等或者key的hash值相等並且equals方法返回true則認為是相同的key,在設定了onlyIfAbsent=false 或者 舊的值為null時將進行替換
  • 當連結串列長度>=8時為了提高查詢效率會將連結串列結構轉化為紅黑樹(紅黑樹細節會在TreeMap的原始碼解讀中詳細描述)
  • modCount用於記錄HashMap的修改次數,HashMap不是執行緒安全的在讀取時修改資料迭代器就會丟擲ConcurrentModificationException異常
  • 儲存的鍵值對的個數>閥值(容量*負載因子)時會進行陣列擴容
  • 負載因子預設為0.75這是一個權衡值。太大會加劇hash衝突,太小會造成空間浪費

如何擴容

/**
 * 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) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            // 沒有超過最大值則擴容為原來陣列長度的2倍
            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"})
            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
                        // 將舊的連結串列拆分成兩個連結串列
                        // 拆分規則:將hash與擴容後新增的參與運算的位進行&運算如果為0則儲存的原始位置,為1則儲存在原始位置+擴容前的容量
                        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;
    }
複製程式碼

總結:

  • 擴容為原來陣列長度的2倍
  • 遍歷舊的資料將其移動到新的陣列中,遇到連結串列時將舊的連結串列拆分成兩個連結串列 拆分規則:將hash與擴容後新增的參與運算的位進行&運算如果為0則儲存的原始位置,為1則儲存在原始位置+擴容前的容量(原因是使用的2次冪的擴充套件即高位增加一位比如16擴容到32 二進位制參與&運算的n-1 由1111變成11111, 即hash需要與新增的高位10000進行&運算 ,運算結果為0即陣列下標為原始位置;運算結果為1則陣列下標為原始位置+擴容前舊的容量)

GET方法為何能快速獲取值

public V get(Object key) {
        Node<K,V> e;
        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;
    // 計算存放在陣列table中的位置
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        // 依次在陣列、紅黑樹、連結串列中查詢(通過equals()判斷)
        // 1. 陣列查詢
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        if ((e = first.next) != null) {
            // 2. 紅黑樹查詢
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            // 3. 連結串列查詢    
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}
複製程式碼

HashMap在日常使用中會有哪些問題?

執行緒不安全

JDK1.7 併發操作時resize方法易出行連結串列遍歷死迴圈,JDK 1.8 轉移資料操作 = 按舊連結串列的正序遍歷連結串列、在新連結串列的尾部依次插入,所以不會出現連結串列 逆序、倒置的情況,故不容易出現環形連結串列的情況。

key為Object型別需要注意哪些問題

  • hashCode() 用於計算儲存位置,選擇不恰當易造成hash碰撞影響效能
  • equals() 保證key在雜湊表中的唯一性
  • hashCode()、equals() (如果進行重寫操作,一定要確保同時被正確重寫)

相關文章