一个demo告诉你HashMap容量变化

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/z28126308/article/details/81101360

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

猜你喜欢

转载自blog.csdn.net/z28126308/article/details/81101360