歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> JDK1.8 HashMap 源碼分析詳解

JDK1.8 HashMap 源碼分析詳解

日期:2017/3/1 9:07:00   编辑:Linux編程

一、概述

以鍵值對的形式存儲,是基於Map接口的實現,可以接收null的鍵值,不保證有序(比如插入順序),存儲著Entry(hash, key, value, next)對象。


二、示例

public static void main(String[] args){
    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("上海", 1);
    map.put("北京", 2);
    map.put("廣州", 3);
    map.put("天津", 4);
    map.put("重慶", 5);

    for(Map.Entry<String, Integer> entry : map.entrySet()) {
        System.out.println(entry.getKey() + ": " + entry.getValue());
    }
}

IntelliJ IDEA 調試,通過Variables我們能看到這樣的儲存方式:


三、HashMap存儲的數據結構

3.1 數據結構

通過示例調試可以總結出HashMap示例存儲的數據結構:

3.2 數據結構核心代碼

3.2.1 table

transient Node<K,V>[] table;

3.2.2 Node

Node是HashMap的一個內部類,單向鏈表實現方式

static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;    //用來定位數組索引位置
    final K key;
    V value;
    Node<K,V> next;    //鏈表的下一個node

    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;
    }
}

3.2.3 TreeNode 紅黑樹

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);
    }

    //返回當前節點的根節點
    final TreeNode<K,V> root() {
        for (TreeNode<K,V> r = this, p;;) {
            if ((p = r.parent) == null)
                return r;
            r = p;
        }
    }

    以下省略... ...
}

四、HashMap主要屬性

//默認初始容量為16,必須為2的冪
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;  

//最大容量為2的30次方
static final int MAXIMUM_CAPACITY = 1 << 30;  

////默認加載因子0.75,當HashMap的數據大小>=容量*加載因子時,HashMap會將容量擴容
static final float DEFAULT_LOAD_FACTOR = 0.75f;  

//鏈表長度大於8時,將鏈表轉化為紅黑樹
static final int TREEIFY_THRESHOLD = 8;  

//如果發現鏈表長度小於 6,則會將紅黑樹重新退化為鏈表
static final int UNTREEIFY_THRESHOLD = 6;  

//轉變成樹之前進行一次判斷,只有鍵值對數量大於64才會發生轉換。這是為了避免在哈希表建立初期,多個鍵值對恰好被放入了同一個鏈表中而導致不必要的轉化。
static final int MIN_TREEIFY_CAPACITY = 64;  //MIN_TREEIFY_CAPACITY>= 4 * TREEIFY_THRESHOLD

//下次擴容的臨界值,size>=threshold就會擴容,threshold=容量*加載因子
int threshold;

final float loadFactor;

// 修改次數
transient int modCount;

五、HashMap的部分源碼分析

在看到3.1的圖時,可能會有疑問,廣州為什麼放到上海的鏈表中,帶著問題我們往下看。

5.1 put實現

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;
    // tab為空則創建
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    // 計算index,並對null做處理
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        // 節點key存在,直接覆蓋value
        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) {
                    // 在Node添加到尾部
                    p.next = newNode(hash, key, value, null);
                    // 若鏈表長度大於8,則轉換為紅黑樹進行處理
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                // key已經存在,直接覆蓋value
                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;
        }
    }
    // 如果本次新增key之前不存在於HashMap中,modCount加1,說明結構改變了
    ++modCount;
    // 如果大於threshold, 擴容
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; Node<K,V> e;
    //當tab.length<MIN_TREEIFY_CAPACITY 時還是進行resize
    if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
        resize();
    // key存在,轉化為紅黑樹
    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. 索引的計算:
    在計算索引時,這個值必須在[0,length]這個左閉右開的區間中,基於這個條件,比如默認的table長度為16,代入公式 (n - 1) & hash,結果必然是存在於[0,length]區間范圍內。這裡還有個小技巧,在容量一定是2^n的情況下,h & (length - 1) == h % length,這裡之所以使用位運算,我想也是因為位運算直接由計算機處理,效率要高過%運算。

  2. 轉化紅黑樹:
    在put方法中,邏輯是鏈表長度大於(TREEIFY_THRESHOLD -1)時,就轉化為紅黑樹, 實際情況這只是初步判斷,在轉化的方法treeifyBin()方法中會進行二次校驗,當tab.length

5.2 hash實現

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

這個函數大概的作用就是:高16bit不變,低16bit和高16bit做了一個異或。根據注釋及個人理解,這樣的做的原因是因為Java中對象的哈希值都32位整數,高位與低位異或一下能保證高低位都能參與到下標計算中,即使在table長度比較小的情況下,也能盡可能的避免碰撞。
舉例:

通過以上計算,也正好證明,為什麼廣州會成為上海的next節點。

5.3 resize實現

final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table;
    int oldCap = (oldTab == null) ? 0 : oldTab.length;  // 獲取原HashMap數組的長度。
    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);
    }
    // 計算新的resize上限
    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;
    // 遍歷桶,然後對桶中的每個元素進行重新hash
    if (oldTab != null) {
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;  // 原table地址釋放
               // 單節點處理 
               if (e.next == null) 
                    newTab[e.hash & (newCap - 1)] = e;  // 重新hash放入新table中
                // 紅黑樹處理
                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) {  // 低位鏈表,注意與的對象是oldCap,而不是 oldCap-1
                            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);
                    // 低位鏈表保持原索引放入新table中
                    if (loTail != null) {
                        loTail.next = null;
                        newTab[j] = loHead;
                    }
                    // 高位鏈表放入新table中,索引=原索引+oldCap
                    if (hiTail != null) {
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}

從resize() 的實現中可以看出,在擴容時,針對table,如果桶的位置是單節點鏈表,那麼index =(hash & (newTab.length - 1)),直接放入新表。紅黑樹另外處理。若是多節點鏈表,會產生高低和低位鏈表,即:hash & length=0為低位鏈表、hash & length=length為高位鏈表。低位鏈表保持原索引放入新table中,高位鏈表index=oldTab.index + oldTab.length = hash & (newTab.length-1)

為什麼要分高低位鏈表?,試想若是全部都使用index =(hash & (newTab.length - 1))計算,此時因為是基於下標存儲,從而導致在index沖突的情況下,多元素鏈表的追加出現額外的時間(尋址等)或空間(輔助參數、結構等)上的開銷。分高低位鏈表,相比先保存好數據再尋找追加效率更好,也是極好的優化技巧。

5.4 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;
    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;
}

5.5 remove實現

public V remove(Object key) {
    Node<K,V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null ? null : e.value;
}

final Node<K,V> removeNode(int hash, Object key, Object value, boolean matchValue, boolean movable) {
    Node<K,V>[] tab; Node<K,V> p; int n, index;
    if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) {
        Node<K,V> node = null, e; K k; V v;
        // 直接命中
        if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
            node = p;
        else if ((e = p.next) != null) {
            // 紅黑樹中查找
            if (p instanceof TreeNode)
                node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
            else {
                // 鏈表中查找
                do {
                    if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
                        node = e;
                        break;
                    }
                    p = e;
                } while ((e = e.next) != null);
            }
        }
        // 命中後刪除
        if (node != null && (!matchValue || (v = node.value) == value || (value != null && value.equals(v)))) {
            if (node instanceof TreeNode)
                ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
            else if (node == p)
                tab[index] = node.next;  // 鏈表首元素刪除
            else
                p.next = node.next;  //多元素鏈表節點刪除
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}

5.6 containsKey實現

public boolean containsKey(Object key) {
    return getNode(hash(key), key) != null; 
}

5.7 containsValue實現

public boolean containsValue(Object value) {
    Node<K,V>[] tab; V v;
    if ((tab = table) != null && size > 0) {
        // table遍歷
        for (int i = 0; i < tab.length; ++i) {
            // 多元素鏈表遍歷
            for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                if ((v = e.value) == value || (value != null && value.equals(v)))
                    return true;
            }
        }
    }
    return false;
}

六、總結

6.1 為什麼需要負載因子?

加載因子存在的原因,還是因為要減緩哈希沖突,例如:默認初始桶為16,或等到滿16個元素才擴容,某些桶裡可能就會有多個元素了。所以加載因子默認為0.75,也就是說大小為16的HashMap,擴容臨界值threshold=0.75*16=12,到了第13個元素,就會擴容成32。

6.2 加載因子減小?

在構造函數裡,設定小一點的加載因子,比如0.5,甚至0.25。
若是一個長期存在的Map,並且key不固定,那可以適當加大初始大小,同時減少加載因子,降低沖突的機率,也能減少尋址的時間。用空間來換時間,這時也是值得的。

6.3 初始化時是否定義容量?

通過以上源碼分析,每次擴容都需要重創建桶數組、鏈表、數據轉換等,所以擴容成本還是挺高的,若初始化時能設置准確或預估出需要的容量,即使大一點,用空間來換時間,有時也是值得的。

6.4 String型的Key設計優化?

如果無法保證無沖突而且能用==來對比,那就盡量搞短點,試想一個個字符的equals都是需要花時間的。順序型的Key,如:k1、k2、k3...k50,這種key的hashCode是數字遞增,沖突的可能性實在太小。

for(int i=0;i<100;i++){
    System.out.println(key+".hashCode="+key.hashCode());
}

結果:
K0.hashCode = 2373
K1.hashCode = 2374
K2.hashCode = 2375
K3.hashCode = 2376
K4.hashCode = 2377
... ...

Copyright © Linux教程網 All Rights Reserved