沒人比我更懂 HashMap :)

Anonymous發表於2020-11-04

哈,標題開個玩笑,0202 年的段子哈。

一、首先看一下 HashMap 的建構函式

/**
     * 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); // 奇怪的是這裡初始化閾值沒有用到負載因子。
    }

第一個引數是初始化容量大小,第二個引數是負載因子。

對這兩個引數有如下介紹:

* <p>An instance of <tt>HashMap</tt> has two parameters that affect its
 * performance: <i>initial capacity</i> and <i>load factor</i>.  The
 * <i>capacity</i> is the number of buckets in the hash table, and the initial
 * capacity is simply the capacity at the time the hash table is created.  The
 * <i>load factor</i> is a measure of how full the hash table is allowed to
 * get before its capacity is automatically increased.  When the number of
 * entries in the hash table exceeds the product of the load factor and the
 * current capacity, the hash table is <i>rehashed</i> (that is, internal data
 * structures are rebuilt) so that the hash table has approximately twice the
 * number of buckets.

機翻的意思就是:

HashMap 的例項有兩個影響其效能的引數:初始容量和負載因子。

容量是雜湊表中的桶數,初始容量就是建立雜湊表時的容量。

負載因子是一種度量方法,用來衡量在自動增加雜湊表的容量之前,雜湊表允許達到的滿度。

當雜湊表中的條目數超過負載因子和當前容量的乘積時,雜湊表將被重新雜湊(即重新構建內部資料結構),

這樣雜湊表的桶數大約是原來的兩倍。

/**
 * The maximum capacity, used if a higher value is implicitly specified
 * by either of the constructors with arguments.
 * MUST be a power of two <= 1<<30.
 */
static final int MAXIMUM_CAPACITY = 1 << 30;

最大的容量是 2 的 30 次方,因為 int 型別最大值是 2 的 31 次方減一。容量還必須是 2 的次方數。

 * <p>This implementation provides constant-time performance for the basic
 * operations (<tt>get</tt> and <tt>put</tt>), assuming the hash function
 * disperses the elements properly among the buckets.  Iteration over
 * collection views requires time proportional to the "capacity" of the
 * <tt>HashMap</tt> instance (the number of buckets) plus its size (the number
 * of key-value mappings).  Thus, it's very important not to set the initial
 * capacity too high (or the load factor too low) if iteration performance is
 * important.

另外不要將容量設定太高,或者將負載因子設定太低,這都會影響效能。

// The next size value at which to resize (capacity * load factor).
int threshold;

閾值,等於容量和負載因子的乘積,如果 table.length 大於 閾值,就得進行 2 倍擴容。

接下來看看 tableSizeFor 方法,也就是計算閾值的:

/**
 * Returns a power of two size for the given target capacity.
 */
static final int tableSizeFor(int cap) {
    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;
}

翻譯的意思是返回給定目標容量的 2 的冪,也就是大於且最接近給定目標容量的最小 2 的冪。

這段程式碼可能看著不太好理解,我們假設 n 的最高位的 1 在位置 i 上,>>> 表示無符號右移。

(>>> 和 >> 的區別就是前者高位不管正式負數都取0,後者正數取 0,負數取 1)。

右移一位再和原來的值進行或操作,那麼結果位置 i 和 i-1 的值一定也為 1。

同理,最後結果一定是 0 ~ i 位都為 1,再加 1 的話,就是最接近給定值的最小2的冪。

另外如果 cap 為  0 的話,那麼就是所有位都是 1 了,n 就小於 0,閾值就為 1。

現在我們在來看下另外的三個建構函式:

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

對於前兩個就不用說了,預設的負載因子為 0.75,為什麼要取這個值呢?

 * <p>As a general rule, the default load factor (.75) offers a good
 * tradeoff between time and space costs.  Higher values decrease the
 * space overhead but increase the lookup cost (reflected in most of
 * the operations of the <tt>HashMap</tt> class, including
 * <tt>get</tt> and <tt>put</tt>).  The expected number of entries in
 * the map and its load factor should be taken into account when
 * setting its initial capacity, so as to minimize the number of
 * rehash operations.  If the initial capacity is greater than the
 * maximum number of entries divided by the load factor, no rehash
 * operations will ever occur.

機翻如下:

作為一般規則,預設的負載係數(.75)在時間和空間成本之間提供了一個很好的折衷。

較高的值減少了空間開銷,但增加了查詢成本(反映在HashMap類的大部分操作中,包括get和put)。

在設定初始容量時,應該考慮對映中的預期條目數及其負載因子,以便最小化重雜湊操作的數量。

如果初始容量大於最大條目數除以負載因子(初始容量和負載因子的乘積大於最大條目數),則不會發生重新雜湊操作。

接下來看看 putMapEntries 方法,最初構造時為假,否則為真。

    /**
     * Implements Map.putAll and Map constructor.
     *
     * @param m the map
     * @param evict false when initially constructing this map, else
     * true (relayed to method afterNodeInsertion).
     */
    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            if (table == null) { // pre-size // table 沒有被初始化過(也就是構建函式是呼叫的),就初始化一下閾值
                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)   // table 已經被初始化過了,長度大於閾值需要進行擴容處理
                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);
            }
        }
    }

 table 就是儲存 Map 鍵值對的陣列,並根據需要調整大小,長度總是2的冪。

    /**
     * The table, initialized on first use, and resized as
     * necessary. When allocated, length is always a power of two.
     * (We also tolerate length zero in some operations to allow
     * bootstrapping mechanics that are currently not needed.)
     */
    transient Node<K,V>[] table;

Node 就是一個靜態內部類,先看看就行,這個我們稍後再作分析。

    /**
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
     */
    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;
        }
    }

我們目前看的是構建時候呼叫,就只看構建時候走的邏輯。那麼我們看下 putVal 方法:

    /**
     * Implements Map.put and related methods.
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @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;
        if ((tab = table) == null || (n = tab.length) == 0)  // table 還未被初始化過,進行初始化。
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)  // 如果這個表裡沒有這個 key 的雜湊,就把這個鍵值對存表裡
            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)))) // 先比對第一個節點的值
                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) {  // 如果找不到,那麼就將這個鍵值對存進去,並判斷是否到達了要轉換成紅黑樹的條件
                        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;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null) // 如果為 onlyIfAbsent 為 true,不改變現在的值
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;   // 用於記錄修改對映的數量,該欄位用於使 HashMap 集合檢視上的迭代器快速失效
        if (++size > threshold) // 說明找不到該 key 的鍵值對,就插入進去
            resize();
        afterNodeInsertion(evict);
        return null;
    }

如果 table 為空的話,我們來看下 resize 方法,蠻長的,初始化或者給表的長度加倍:

    /**
     * Initializes or doubles table size.  If null, allocates in
     * accord with initial capacity target held in field threshold.
     * Otherwise, because we are using power-of-two expansion, the
     * elements from each bin must either stay at same index, or move
     * with a power of two offset in the new table.
     *
     * @return the 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) {    // 原來的 table 有值
            if (oldCap >= MAXIMUM_CAPACITY) { // 容量大於最大容量,閾值設為最大。
                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 // 原來的 table 已經初始化過,但是table 裡沒有資料,新容量等於原來的閾值。
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults // table 還沒有初始化過,進行初始化。
            newCap = DEFAULT_INITIAL_CAPACITY; 
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) { // 原來的 table 已經初始化過,但是 table 裡沒有資料,計算一下新閾值。
            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) {   // 如果原來 table 有值,就把值放進新的 table 裡.
            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;
    }

二、未完待續......

三、ArrayList 擴容機制

相關文章