HashMap 初始化大小以及扩增规则

大家都知道 hashmap的数据结构 链表(Node<Key,Value>)组成的数组(Node[] table),同一个链表中的数据,key的hashcode相同,Capacity 为table数组的容量(并不是hashmap里面拥有元素的容量),size为所有元素的和。网上找的图片

《HashMap 初始化大小以及扩增规则》

先看几个成员变量 很简单的英文

    /**
     * The table, initialized on first use, and resized as
     * necessary. When allocated, length is always a power of two.
     * 在第一次用的时候初始化,长度是2的幂
     */
    transient Node<K,V>[] table;
    /**
     * The number of key-value mappings contained in this map.
     */
    transient int size;
    // size大于这个值的时候 resize (capacity * load factor).
    int threshold;
    // 加载因子 默认0.75 
    final float loadFactor;

构造函数 初始化值

    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
    
    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);
    }

通过方法tableSizeFor可知 初始化时 capacity(构造函数传参 容量) 不会存到HashMap的成员变量中,threshold初始值为不小于capacity最小的2的n次幂 如1->1 2->2 3->4 4->4 5->8…8->8 9->16。仅仅初始化的时候 threshold为2的n次幂,第一次调用put前,则为2的n次幂乘以loadFactor, 如 3 6 12 24 48

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

put 方法 当初始化完成后 第一次调用put方法,因为(table==null) 所以第一次put会resize(),通过这次resize() threshold 即变为原先threshold的loadFactor倍(默认0.75)

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

上面说过 capacity不作为一个成员变量存到HashMap中,但如何取到capacity的值呢?通过 table.length, table为空 代表刚刚初始化,还有么put值,所以可以直接返回threshold,table不为空,返回table.length

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

resize方法可以归纳为 table(capacity)大小(4 8 16 32 64)增大一倍,threshold(3 6 12 24 48)增大一倍

重点—- 上面已经说过 HashMap容量为table的大小,并不是拥有元素的上界,但resize的判定条件却是以++size>threshold 来判断的 所以有极端的情况,当所有的key的hashcode为一样时,所有key-value数据都存到了table[]的一个链表中,其他 capacity-1个链表都为空,但是,当size>threshold时,还是会把threshold与table扩容一倍,造成非常大的容量浪费 例子如下

public class DemoMain {
    public static void main(String[] args) {
        Map<Key, Object> map = new HashMap<>(5);
        for (int i = 1; i <= 10000; i++) {
            map.put(new Key("key-" + i), "value-" + i);
        }
        System.err.println(map);
    }

    static class Key {
        private String name;

        public Key(String name) {
            this.name = name;
        }

        @Override
        public int hashCode() {
            return 1; //代表所有的key-value数据都会放到hashmap的同一个链表中
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Key other = (Key) obj;
            if (name == null) {
                if (other.name != null)
                    return false;
            } else if (!name.equals(other.name))
                return false;
            return true;
        }
    }
}
    原文作者:乘以零
    原文地址: https://www.jianshu.com/p/f67e4ac263aa
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞