为什么要使用“阈值”字段来保持初始容量,而不是使用诸如“ initialCapacity”之类的更清晰的字段?

时间:2019-04-23 08:28:10

标签: java hashmap

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); // here, threadshold is actually initial capacity
}

阅读代码时,我有些困惑。我的问题是,为什么要使用字段threshold来保持初始容量,而不是使用其他更清晰的字段,例如initialCapacity


编辑:我没有注意到构造函数接受参数initialCapacity,我认为构造函数参数initialCapacity应该是specifiedInitialCapacity

1 个答案:

答案 0 :(得分:0)

因为HashMaps增长超过一次,并且阈值是一个动态值。它会在地图的生命周期中发生变化,并在调整地图大小时进行调整。

threshold(1.8 openjdk)的Javadoc:

/**
 * The next size value at which to resize (capacity * load factor).
 *
 * @serial
 */
// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated, this
// field holds the initial array capacity, or zero signifying
// DEFAULT_INITIAL_CAPACITY.)
int threshold;

由于可以调整地图的大小,因此初始容量就是这样,并且阈值最初只是相同的。