HashMap 的共有三个构造方法,源码如下:
```java
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
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);
}
```
初看源码,可以发现,被 final 修饰的 loadFactor 一定会在构造方法中被初始化。
带参构造方法主要做的就是对 initialCapacity 和 loadFactor 的校验工作,并且会通过 tableSizeFor 方法计算其合理的初始容量,由于此时 table 数组尚未实例化,所以该合理的初始容量被暂存在 threshold 属性中,由其代为保管。