沒人比我更懂 HashMap :)

哈,標題開個玩笑,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 就是一個靜態內部類,也就是存儲 Map 的實體。

    /**
     * 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 方法 和 hash 方法:

hash 方法(每個 key 的 hash 是不會變的,這個無符號右移 16 位的操作可以減少衝突):

/**
* Computes key.hashCode() and spreads (XORs) higher bits of hash
* to lower. Because the table uses power-of-two masking, sets of
* hashes that vary only in bits above the current mask will
* always collide. (Among known examples are sets of Float keys
* holding consecutive whole numbers in small tables.) So we
* apply a transform that spreads the impact of higher bits
* downward. There is a tradeoff between speed, utility, and
* quality of bit-spreading. Because many common sets of hashes
* are already reasonably distributed (so don't benefit from
* spreading), and because we use trees to handle large sets of
* collisions in bins, we just XOR some shifted bits in the
* cheapest possible way to reduce systematic lossage, as well as
* to incorporate impact of the highest bits that would otherwise
* never be used in index calculations because of table bounds.
*/
static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); // 保留高16位,將高16位和低16位進行異或的結果作爲低16位。
    }
public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

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 的哈希,就把這個鍵值對存表裏,因爲是與操作(n是2的冪),所以擴容對位置沒有影響1
            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;
    }

 

二、我們再來看看常用的 get 和 set 方法(感覺沒啥好解釋的了):

    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
    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;
    }

 

三、ArrayList 擴容機制

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章