编程语言
首页 > 编程语言> > HashMap源码(一)

HashMap源码(一)

作者:互联网

本文主要是从学习的角度看HashMap源码

HashMap的数据结构

HashMap的初始化

    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
    // 这里的MAXIMUM_CAPACITY=1 << 30(问题一: 为什么是30?)
        if (initialCapacity > MAXIMUM_CAPACITY)
        // 如果传入初始值大于1<<30 则默认值为最大;
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        // 这里是根据传入的初始值算得 大于输入参数且最近的2的整数次幂的数
        this.threshold = tableSizeFor(initialCapacity);
    }
问题一:MAXIMUM_CAPACITY = 1 << 30
问题二:initialCapacity初始值为16

因为在使用是2的幂的数字的时候,Length-1的值是所有二进制位全为1,这种情况下,index的结果等同于HashCode后几位的值。
只要输入的HashCode本身分布均匀,Hash算法的结果就是均匀的。
这是为了实现均匀分布。

问题三: loadFactor默认值0.75

JDK 1.7中:
As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.

接下来我们会具体看下HashMap的resize方法

博文推荐:https://www.hollischuang.com/archives/4320 (掘金看见的,写的很好)

标签:HashMap,16,初始值,initialCapacity,源码,0.75,loadFactor
来源: https://www.cnblogs.com/heyouxin/p/12251577.html