图解debug——实例化一个HashMap,初始化容量到底应该设置多大

一、结论

首先先放出结论,根据阿里巴巴java开发规范中,第一章第五节第9点;

【推荐】集合初始化时,指定集合初始值大小。
说明:HashMap 使用 HashMap(int initialCapacity) 初始化, 正例:initialCapacity = (需要存储的元素个数 / 负载因子) + 1。注意负载因子(即 loader
factor)默认为 0.75,如果暂时无法确定初始值大小,请设置为 16(即默认值)。
反例:HashMap 需要放置 1024 个元素,由于没有设置容量初始大小,随着元素不断增加,容
量 7 次被迫扩大,resize 需要重建 hash 表,严重影响性能。

也就是公式:
n ----- 需要存储的元素个数
c ----- 建议设置容量大小
c = (n * 4 / 3) + 1
如果我们需要存3个,按这个公式应该设置为5,而不是4,其实它的容量也不是5,而是8。

二、代码解析

2.1 断点

首先按照我们平时的习惯,存储3个,设置容量为3
在map实例化和put方法代码打上断点

   public static void main(String[] args) {
   		int n = 3;
        HashMap<Object, Object> map = new HashMap<>(n);
        map.put("a","a");
        map.put("b","a");
        map.put("c","a");
        System.out.println(1);
    }

并且在HashMap的putVal()方法打上两个断点,所有put方法都会进入到这个方法中

  /**
     * 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)
        	//下面一行代码打上断点
  *          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;
        //下面一行代码打上断点
  *      if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

在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);
    }

在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) {
            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
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        //打上断点
   *     if (newThr == 0) {
            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) {
                    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;
    }
2.2 debug
a、 3个元素容量为3

在运行时,先把HashMap的断点先跳过,因为很多类中都涉及到HashMap使用,等运行到我们main方法使用HashMap时再打开HashMap的断点,debug程序。

第一步先是到了构造方法的断点
在这里插入图片描述
tableSizeFor这个方法,能获取到入参往上取的一个2次幂值。比如我们的3,就会得到4。 5就会得到8
在这里插入图片描述
这里还只是将阈值thr设置成了4,而不是容量cap,容量还是3

继续F8,到第一次put方法调用,进入到putval断点
在这里插入图片描述
可以看到因为table为null,调用到了resize方法,也就是不管初始化容量怎么设置,第一次put都会resize一次
进入到resize方法,可以看到有几个变量,oldCap上一次的容量,oldThr上一次阈值,newCap新容量,newThr新阈值
在这里插入图片描述
在这里插入图片描述
因为oldCap为0,进入else if,将newCap=oldThr,也就是这里才将容量设置为我们那个实例化HashMap的初始化容量的往上取二次幂的值
在这里插入图片描述
同时继续往下执行,因为newThr=0,根据负载因子计算出阈值,得到newThr=4*0.75=3,并真正赋值给全局变量,真正的阈值threshold
在这里插入图片描述
跳到resize方法结尾,看到几个变量现在的值如下
在这里插入图片描述
跳出resize方法,回到putval方法,到下一次可能resize的地方
在这里插入图片描述
这里发现++0<3,所以不会进入resize方法

再到第二次put,按F8,发现前面的断点都没有触发,再一次到了if (++size > threshold)判断这里,这里size是1,也就是++1<3,不会进入resize方法

后面的put也是,没有进入resize方法。

上面是3个元素,设置容量为3.结论,只在第一次put的时候resize了一次。

b、 5个元素容量为5

如果是5个元素,容量为5呢?

根据上面我们知道,HashMap会在实例化的时候,将阈值临时设置为往上取二次幂,也就是8,第一次put的时候,设置容量为8,阈值是8*0.75=6

进入第一次put时的resize方法底部的断点可以看到,确实是这样
在这里插入图片描述
并且根据putval方法底部的

if (++size > threshold)
            resize();

可以得知,第7次put,size为6(size从0开始)才会第二次调用resize方法。
结论 只会第一次put的时候resize

c、容量为7元素为7

这个时候同理容量会变成8,
到了第7次put的时候,size是6,if (++size > threshold)满足条件,第二次resize,容量变成16,阈值变成12

三、结论

根据debug可知,HashMap在实例化的时候不会初始化容量。第一次put的时候才会设置容量,阈值,并且会进行一次resize

我们在构造函数传的值,如果不是二次幂,都会往上取二次幂的值,比如5,得8,设置为容量
扩容除了第一次put的时候,还会发生在达到阈值的时候

其实阿里的公式也不是最精准的,在我们要存放的元素个数正好是阈值的时候,比如6,经过公式得到9,HashMap再取二次幂,容量为16,其实6个元素的话容量为8是可以刚刚好的,不过也不用太计较这些了

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值