Api文档里说:
An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created.
代码是这样的:
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);
}
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;
}
也就是说,intialCapacity出了构造方法就没用了,它也没被记下来。被记下来的是this.threshold = tableSizeFor(initialCapacity)。以后第一次put()时,用的是这个threshold来初始化bucket数组。tableSizeFor(c)返回最小的数t,t大于等于c且t是2的整数次幂。
代码写的和文档说的不一样……而且你不看代码是不会知道这件事的。比如用9、10、11、12、13、14、15、16作为initialCapacity来初始化,效果是完全一样的!
这种事,也很难说算是个什么事。但作为用Java的人,总是不免觉得别扭。把代码写的和文档一样又不是很难,也是应该的。何必要这样呢?