HashMap之容量大小与扩容

作为Java中最常用的K-V数据类型,HashMap的源码有很多地方值得细读。

首先,需要区分清楚几个概念:capacity、size、threshold

容量(capacity)是指当前map最多可以存放多少个元素,大小(size)是指当前map已经存放了多少个k-v键值对。threshold是扩容的阈值,当size超过阈值后,便需要对map进行扩容。也就是说,一般情况下,map当中的键值对数量不会达到其容量上限。阈值一般为:capacity*loadFactor(负载因子)

 

一、默认情况下,new HashMap()得到的对象,其容量为16,负载因子为0.75

    /**
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

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

    /**
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

二、在初始化map时,若指定了容量大小,那么,实际的容量值为大于等于该数的第一个2的幂的值。

即:tableSizeFor方法结果(1  => 1 ; 5=> 8 ; 8=>8 ; 9=> 16)

在下面的代码执行时:

Map m = new HashMap(5);


实际调用了:

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

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

这里的tableForSize方法,位移操作,在进行按位或,

实际上是将一个二进制数从最高位不为0起,将其后面所有的位数都置为1.例如:

0010 0000   (原始数据)
0001 0000    (右移1位)
-------------(按位 或)
0011 0000   
0000 1100
-------------
0011 1100
0000 0011
-------------
0011 1111

所以,tableForSize方法,实际上是将一个32位的数据,从最高位不为0起,后面全部置为1,然后再+1,结果就是 最接近指定大小的数的2的幂

具体可以参考下面文章的分析:https://www.hollischuang.com/archives/2431

值得注意的是,上面的源码中,是将tableForSize的值赋值给了threshold, 那为何说是我们初始化容量(capacity)的大小为该值呢?

因为在Map初始化时,是第一次向map添加数据才会触发的。第一次put数据时,调用:

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    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 {
           ...
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

注意上面,putVal会判断table是否为null

if ((tab = table) == null || (n = tab.length) == 0)

如果为null,则调用resize方法:

n = (tab = resize()).length;

而resize方法中:

    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作为了初始化的容量大小。

 不过,对于初始化容量为1时,即 new HashMap(1);此刻的capacity有一点不同,就是在没有调用put方法时,capacity==1 ,再调用put之后,capacity ==2。这是因为发生了扩容

        HashMap<String,String> m = new HashMap(1); 
        //m.put("",""); //调用之后,capacatiy会等于2
        Method method = m.getClass().getDeclaredMethod("capacity");
        method.setAccessible(true);
        System.out.println(method.invoke(m)); // 输出:1 

其它情况下:

 

        HashMap<String,String> m = new HashMap(3); 
        //m.put("",""); //调用之后,capacatiy会等于4,调用与否都是一致的
        Method method = m.getClass().getDeclaredMethod("capacity");
        method.setAccessible(true);
        System.out.println(method.invoke(m)); // 输出:4 

实际上,调用capacity方法时:

    final int capacity() {
        return (table != null) ? table.length :
            (threshold > 0) ? threshold :
            DEFAULT_INITIAL_CAPACITY;
    }

也就是说,如果已经初始化了table数组,则返回数组的大小,否则返回threadhold.

 

三、扩容时的操作:

每次触发扩容时,capacity会变为原来的两倍。 

 

参考:https://www.hollischuang.com/archives/2431 

posted @ 2019-12-09 16:01  sliec  阅读(4373)  评论(0编辑  收藏  举报