美文网首页Java
关于 Java 中的 HashMap 常见问题总结

关于 Java 中的 HashMap 常见问题总结

作者: 虹猫日志 | 来源:发表于2019-12-04 22:53 被阅读0次

    1. HashMap的大小为什么必须是2的幂次

    • 需要注意的是,创建HashMap的时候并没有将空间开辟出来,只要当你第一次往里面扔数据的时候才开辟空间,避免了资源浪费。

    首先看下HashMap中定义的初始容量大小:

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

    我们一般使用空参构造,也就是说put的时候进行空间开辟,那么不妨看下代码是怎么做的:

    //首先找到put源码
    public V put(K key, V value) {
          return putVal(hash(key), key, value, false, true);
      }
    //put调用了putVal进行跟进这里只拿一部分
    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;//看到这里猜测没有初始化,调用resize()先进行初始化
         if ((p = tab[i = (n - 1) & hash]) == null)
    ........
    //看看 resize()又是什么。结果直接看注释,就发现这里说明了为空使用默认值初始化,否则,我们使用的是2的幂扩展
    /**
    * 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);//不出意外就是这里
        }
    ........
    

    到此应该明了空参默认为什么是大小为16,而且是大小是2的幂次。
    接着我们看看有参构造是怎么做的:

    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;
       //上述是一堆判断,这里tableSizeFor明显是表大小的关键
        this.threshold = tableSizeFor(initialCapacity);
    }
    // 跟进tableSizeFor方法
    /**
    * Returns a power of two size for the given target capacity. (返回给定目标容量的两倍幂)
    */
    static final int tableSizeFor(int cap) {
        int n = -1 >>> Integer.numberOfLeadingZeros(cap - 1);
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }
    

    看完有参构造后发现,tableSizeFor方法将你给定的大小扩容两倍幂。关键是为么都要使用2的幂,我们来看最关键的代码。

    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    //i = (n - 1) & hash 这是关键
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    

    解释:只有当大小是2的n次方,length-1的值进行转换,后面的二进制位全为1,进行按位与运算才能非常快速的拿到数组的下标,分别放在不同的哈希桶中(index = key值 (n - 1) & hash ≈ hash % n)。二进制的运算速度远高于取模,结果分布还是均匀的。

    2. HashMap的负载因子为什么默认为0.75

    • 其实这个答案就在源码注释中\color{#ea4335}{默认的负载因子0.75在时间和空间成本之间提供了一个很好的权衡......}这里直接上图:
    负载说明

    3. HashMap在什么情况下链表结构改用树结构

    • 当节点元素个数超过8个的时候改用树结构,个数遵循泊松分布,具体如下图:
    取值说明

    本文是个人初次源码解析,如有错误还请指正

    相关文章

      网友评论

        本文标题:关于 Java 中的 HashMap 常见问题总结

        本文链接:https://www.haomeiwen.com/subject/qjifgctx.html