1. 程式人生 > >一個demo告訴你HashMap容量變化

一個demo告訴你HashMap容量變化

           對HashMap所有了解的都知道HashMap有一個負載因子loadFactor,當HashMap容量超過閥值時將進行擴容,該文就是根據圍繞HashMap的閥值、容量進行探討,這些探討也是源於一開始瞭解HashMap的容量都是通過別人的文章,卻從未自己去體驗測試過。

       該文主要解決之前促使我去探討HashMap及探討中所遇到的問題:

(1)new HashMap(n) 的初始閥值/容量是多少?

(2)為什麼new HashMap(n) put進一個元素後閥值會發生變化?

(3)HashMap達到閥值時擴容的變化規律?

以下將根據問題給出對應的主要程式碼(JDK1.8)進行解答:

(1)new HashMap(n)將涉及以下2個方法,tableResizeFor方法的作用是返回比cap大的最小的一個2的n次冪數字如:cap=15則n=16,cap=23則n=32

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);
}
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)當HashMap首次put元素時,由於對映中的節點table為空,將對HashMap的容量進行resize,將當前的容量設為initCap*loadFactor

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
   //  首次put元素由於table為空將進行resize()
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
   // 容量已滿時觸發
    if ((p = tab[i = (n - 1) & hash]) == null)
        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))))
            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)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    // 容量已滿時進行resize()
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

(3)HashMap達到閥值時擴容則是在比原容量大且最接近原容量的一個2的指數次冪數字*2(拋開MAXIMUM_CAPACITY = 1 << 30討論),這一切都在HashMap的resize()方法進行。以下是個人的測試程式碼及輸出結果圖,可以更清晰地反應HashMap容量變化:

@Test
public void mapThreshold() throws NoSuchFieldException, IllegalAccessException {
    Map<String, Object> map = new HashMap<>(7);
    Field threshold = map.getClass().getDeclaredField("threshold");
    threshold.setAccessible(true);
    System.err.println("threshold:" + threshold.get(map));
    map.put("1", 1);
    System.err.println("threshold:" + threshold.get(map));
    map.put("2", 1);
    map.put("3", 1);
    map.put("4", 1);
    map.put("5", 1);
    map.put("6", 1);
    System.err.println("threshold:" + threshold.get(map));
    map.put("7", 1);
    System.err.println("threshold:" + threshold.get(map));
    map.put("8", 1);
    System.err.println("threshold:" + threshold.get(map));
    IntStream.rangeClosed(9, 33)
            .forEach(e -> {
                map.put(String.valueOf(e), e);
                if (e == 16|| e == 17 || e == 32 || e == 33) {
                    try {
                        System.err.println("threshold:" + threshold.get(map));
                    } catch (IllegalAccessException e1) {
                        e1.printStackTrace();
                    }
                }
            });
}