HashMap 源碼閱讀

HashMap 源碼閱讀

以前讀過一些類的源碼,近來發現都忘了,再讀一遍整理記錄一下。此次讀的是 JDK 11 的代碼,貼上來的源碼會去掉大部分的註釋, 也會加上一些本身的理解。node

Map 接口

這裏提一下 Map 接口與1.8相比 Map接口又新增了幾個方法:
數組

  • 這些方法都是包私有的static方法;
  • of()方法分別返回包含 0 - 9 個鍵值對的不可修改的Map;
  • ofEntries()方法返回包含從給定的entries總提取出來的鍵值對的不可修改的* Map(不會包含給定的entries);
  • entry()方法返回包含鍵值對的不可修改的 Entry,不容許 null 做爲 key 或 value;
  • copyOf()返回一個不可修改的,包含給定 Map 的 entries 的 Map ,調用了ofEntries()方法.

數據結構

HashMap 是如何存儲鍵值對的呢?安全

HashMap 有一個屬性 table:數據結構

transient Node<K,V>[] table;

table 是一個 Node 的數組, 在首次使用和須要 resize 時進行初始化; 這個數組的長度始終是2的冪, 初始化時是0, 所以可以使用位運算來代替模運算.app

HashMap的實現是裝箱的(binned, bucketed), 一個 bucket 是 table 數組中的一個元素, 而 bucket 中的元素稱爲 bin .ide

來看一下 Node , 很顯然是一個單向鏈表:this

static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;
    
    ...
}

固然, 咱們都知道 bucket 的結構是會在鏈表和紅黑樹之間相互轉換的:線程

// 轉換成紅黑樹
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
    treeifyBin(tab, hash);

// 轉換成鏈表結構
if (lc <= UNTREEIFY_THRESHOLD)
    tab[index] = loHead.untreeify(map);

注意在 treeifyBin() 方法中:code

// table 爲 null 或者 capacity 小於 MIN_TREEIFY_CAPACITY 會執行 resize() 而不是轉換成樹結構
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
    resize();

TreeNode 的結構和 TreeMap 類似, 而且實現了 tree 版本的一些方法:

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;

    ...
}

initialCapacity 和 loadFactor

先看一下 HashMap 的4個構造器,能夠發現3個重要的 int :threshold,initialCapacity 和 loadFactor ,其中 threshold 和 loadFactor 是 HashMap 的私有屬性。

HashMap 的 javadoc 中有相關的解釋:

  • capacity,HashMap 的哈希表中桶的數量;
  • initial capacity ,哈希表建立時桶的數量;
  • load factor ,在 capacity 自動增長(resize())以前,哈希表容許的填滿程度;
  • threshold,下一次執行resize()時 size 的值 (capacity * load factor), 若是表沒有初始化, 存放的是表的長度, 爲0時表的長度將會是 DEFAULT_INITIAL_CAPACITY

注意: 構造器中的 initialCapacity 參數並非 table 的實際長度, 而是指望達到的值, 實際值通常會大於等於給定的值. initialCapacity 會通過tableSizeFor() 方法, 獲得一個不大於 MAXIMUM_CAPACITY 的足夠大的2的冪, 來做爲table的實際長度:

static final int tableSizeFor(int cap) {
    int n = -1 >>> Integer.numberOfLeadingZeros(cap - 1);
    return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

loadFactor 的默認值是 0.75f :

static final float DEFAULT_LOAD_FACTOR = 0.75f;

initialCapacity 的默認值是16:

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

capacity 的最大值是1073741824:

static final int MAXIMUM_CAPACITY = 1 << 30;

在 new 一個 HasMap 時,應該根據 mapping 數量儘可能給出 initialCapacity , 減小表容量自增的次數 . putMapEntries() 方法給出了一種計算 initialCapacity 的方法:

float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
         (int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
    threshold = tableSizeFor(t);

這段代碼裏的 t 就是 capacity .

hash() 方法

hash() 是 HashMap 用來計算 key 的 hash 值的方法, 這個方法並非直接返回 key 的 hashCode() 方法的返回值, 而是將 hashCode 的高位移到低位後 再與原值異或.

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

由於 HashMap 用 hash & (table.length-1)代替了 模運算 , 若是直接使用 hashCode() 的返回值的話, 只有hash code的低位(若是 table.length 是2的n次方, 只有最低的 n - 1 位)會參加運算, 高位即便發生變化也會產生碰撞. 而 hash() 方法把 hashCode 的高位與低位異或, 至關於高位也參加了運算, 可以減小碰撞.

舉個例子:
假設 table.length - 1 的 值爲 0000 0111, 有兩個hash code : 0001 0101 和 0000 0101. 這兩個hash code 分別與 table.length - 1 作與運算以後的結果是同樣的: 0000 0101; 將這兩個hash code 的高位和低位異或以後分別獲得: 0001 0100、 0000 0101, 此時再分別與 table.length - 1 作與運算的結果是 0000 0100 和 0000 0101, 再也不碰撞了.

resize()

resize() 方法負責初始化或擴容 table. 若是 table 爲 null 初始化 table 爲 一個長度爲 threshold 或 DEFAULT_INITIAL_CAPACITY的表; 不然將 table 的長度加倍, 舊 table 中的元素要麼呆在原來的 index 要麼以2的冪爲偏移量在新 table中移動:

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)
            // 將舊容量加倍做爲新表容量, 若是新表容量沒達到容量最大值, 而且舊容量大於等於默認容量, threshold 加倍
            newThr = oldThr << 1; // double threshold
    }
    else if (oldThr > 0) // initial capacity was placed in threshold
        // 舊的threshold 不爲 0 , 舊 threshold 做爲新表的容量
        newCap = oldThr;
    else {               // zero initial threshold signifies using defaults
        // 舊 threshold 爲 0 , 用 DEFAULT_INITIAL_CAPACITY 做爲新容量, 用默認值計算新 threshold
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    if (newThr == 0) {
        // 以前沒有計算過新 threshold , 計算 threshold
        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) {
                // 幫助 GC
                oldTab[j] = null;
                if (e.next == null)
                    // 這個桶裏只有一個元素, 此處用位運算代替了模運算
                    newTab[e.hash & (newCap - 1)] = e;
                else if (e instanceof TreeNode)
                    // 若是這個 bucket 的結構是樹, 將這個 bucket 中的元素分爲高低兩部分((e.hash & bit) == 0 就分在低的部分, bit 是 oldCap), 低的部分留在原位, 高的部分放到 newTab[j + oldCap]; 若是某一部分的元素個數小於 UNTREEIFY_THRESHOLD 將這一部分轉換成鏈表形式, 不然就造成新的樹結構
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                else { // preserve order
                    // 將普通結構的 bucket 中的元素分爲高低兩部分, 低的部分留在原位, 高的部分放到 newTab[j + oldCap]
                    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;
}

舉個例子解釋一下高低兩部分的劃分:

  • 擴容前 table.length 是 0000 1000 記爲 oldCap , table.length - 1 是 0000 0111 記爲 oldN;
  • 擴容後 table.length 是 0001 0000 記爲 newCap, table.length - 1 爲 0000 1111 記爲 newN;
  • 有兩個Node, hash ( hash() 方法獲得的值)分別爲 0000 1101 和 0000 0101 記爲 n1 和 n2;

在擴容前, n1 和 n2 顯然是在一個 bucket 裏的, 但在擴容後 n1 & newN 和 n2 & newN 的值分別是 0000 1101 和 0000 0101, 這是須要劃分紅兩部分, 而且把屬於高部分的 bin 移動到新的 bucket 裏的緣由.

擴容後, hash 中只會有最低的4位參加 index 的計算, 所以能夠用第4位來判斷屬於高部分仍是低部分, 也就能夠用 (hash & oldCap) == 0 來做爲屬於低部分的依據了.

查找

查找方法只有 get()getOrDefault() 兩個, 都是調用了 getNode()方法:

public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}

@Override
public V getOrDefault(Object key, V defaultValue) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
}

getNode() 方法

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) {
        // table 已經被初始化且 table 的長度不爲 0 且 對應的 bucket 裏有 bin
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            // 第一個節點的 key 和 給定的 key 相同
            return first;
        if ((e = first.next) != null) {
            // bucket 中還有下一個 bin
            if (first instanceof TreeNode)
                // 是樹結構的 bucket, 調用樹版本的 getNode 方法
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            do {
                // 在普通的鏈表中查找 key
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

遍歷

能夠經過entrySet()keySet()values()分別得到 EntrySetKeySet()Values對象, 他們的迭代器都是HashIterator的子類.

fast-fail 和 modCount

HashMap 不是線程安全的, 而且實現了 fast-fail 機制. 當一個迭代器被建立的時候(或者迭代器自身的 remove() 方法被調用), 會記錄當前的 modCount 做爲期待中的 modCount, 並在操做中先檢查當前 modCount 是否是和舊的 modCount 相同, 不一樣則會拋出ConcurrentModificationException.

任何結構修改(新增或刪除節點)都會改變 modCount 的值.

新增和更新

1.8 以前有4個方法和構造器可以往 HashMap 中添加鍵值對: 以一個Map爲參數的構造器、put()putAll()putIfAbsent(),

public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}

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

public void putAll(Map<? extends K, ? extends V> m) {
    putMapEntries(m, true);
}

@Override
public V putIfAbsent(K key, V value) {
    return putVal(hash(key), key, value, true, true);
}

他們分別調用了putMapEntries()putVal(). 這兩個方法中有一個參數 evict , 僅當初始化時(構造器中)爲 false.

putVal() 方法

來看一下putVal() 方法:

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)
        // table 未被初始化或者長度爲 0 時, 執行 resize()
        n = (tab = resize()).length;
    if ((p = tab[i = (n - 1) & hash]) == null)
        // 對應的 bucket 裏沒有元素, 新建一個普通 Node 放到這個位置
        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))))
            // 第一個節點的 key 和 給定的 key 相同
            e = p;
        else if (p instanceof TreeNode)
            // 樹結構, 調用樹版本的 putVal, 若是樹結構中存在 key, 將會返回相應的 TreeNode, 不然返回 null
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    // 在鏈表中沒有找到 key, 新建一個節點放到鏈表末尾
                    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))))
                    // key 相同 break
                    break;
                p = e;
            }
        }
        if (e != null) { // existing mapping for key
            // key 在 map 中存在
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                // 覆蓋舊值
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    // key 以前在 map 中不存在, 發生告終構變化, modCount 增長 1
    ++modCount;
    if (++size > threshold)
        // 擴容
        resize();
    afterNodeInsertion(evict);
    return null;
}

HashMap 提供了三個回調方法:

void afterNodeAccess(Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { }
void afterNodeRemoval(Node<K,V> p) { }

putMapEntries() 方法

putMapEntries()方法就簡單多了

final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
    int s = m.size();
    if (s > 0) {
        if (table == null) { // pre-size
            // table 尚未初始化, 計算出 threshold
            float ft = ((float)s / loadFactor) + 1.0F;
            int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                     (int)ft : MAXIMUM_CAPACITY);
            if (t > threshold)
                threshold = tableSizeFor(t);
        }
        else if (s > threshold)
            // s 超過了 threshold, 擴容
            resize();
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
            // 調用 putVal() 方法, 將鍵值對放進 map
            K key = e.getKey();
            V value = e.getValue();
            putVal(hash(key), key, value, false, evict);
        }
    }
}

刪除

刪除元素有三個方法, 還有 EntrySet 和 KeySet 的 remove 和 clear 方法:

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

@Override
public boolean remove(Object key, Object value) {
    return removeNode(hash(key), key, value, true, true) != null;
}

public void clear() {
    Node<K,V>[] tab;
    modCount++;
    if ((tab = table) != null && size > 0) {
        size = 0;
        for (int i = 0; i < tab.length; ++i)
            tab[i] = null;
    }
}

removeNode() 方法

removeNode() 方法有5個參數, 說明一下其中兩個:

  • matchValue 爲 true 時, 只在 value 符合的狀況下刪除;
  • movable 爲 false 時, 刪除時不移動其餘節點, 只給樹版本的刪除使用.
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) {
        // table 已經被初始化且 table 的長度不爲 0 且 對應的 bucket 裏有 bin
        Node<K,V> node = null, e; K k; V v;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            // 第一個的 key 和給定的 key 相同
            node = p;
        else if ((e = p.next) != null) {
            // bucket 中有不止一個 bin
            if (p instanceof TreeNode)
                // 樹結構, 調用樹版本的 getNode
                node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
            else {
                // 在普通的 bucket 中查找 node
                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)))) {
            // 找到了 node , 而且符合刪除條件
            if (node instanceof TreeNode)
                // 樹結構, 調用樹版本的 removeNode , 若是節點過少, 會轉換成鏈表結構
                ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
            else if (node == p)
                // node 是鏈表的第一個元素
                tab[index] = node.next;
            else
                // 不是第一個元素
                p.next = node.next;
            // 結構變化 modCount + 1
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}

總結

  • HashMap 是一個基於哈希表的裝箱了的 Map 的實現; 它的數據結構是一個桶的數組, 桶的結構多是單向鏈表或者紅黑樹, 大部分是鏈表.
  • table 的容量是2的冪, 所以能夠用更高效的位運算替代模運算.
  • HashMap 使用的 hash 值, 並非 key 的 hashCode()方法所返回的值, 詳細仍是看上面吧.
  • 一個普通桶中的 bin 的數量超過 TREEIFY_THRESHOLD, 而且 table 的容量大於 MIN_TREEIFY_CAPACITY, 這個桶會被轉換成樹結構; 若是 bin 數量大於TREEIFY_THRESHOLD , 但 table 容量小於 MIN_TREEIFY_CAPACITY, 會進行擴容.
  • 每次擴容新 table 的容量是老 table 的 2 倍.
  • 擴容時, 會將原來下標爲 index 的桶裏的 bin 分爲高低兩個部分, 高的部分放到 newTab[index + oldCap] 上, 低的部分放在原位; 若是某部分的 bin 的個數小於 UNTREEIFY_THRESHOLD 樹結構將會轉換成鏈表結構.
  • ... ... (不想寫了, 之後再改吧)
相關文章
相關標籤/搜索