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出了構(gòu)造方法就沒用了,它也沒被記下來。被記下來的是this.threshold = tableSizeFor(initialCapacity)。以后第一次put()時,用的是這個threshold來初始化bucket數(shù)組。tableSizeFor(c)返回最小的數(shù)t,t大于等于c且t是2的整數(shù)次冪。
代碼寫的和文檔說的不一樣……而且你不看代碼是不會知道這件事的。比如用9、10、11、12、13、14、15、16作為initialCapacity來初始化,效果是完全一樣的!
這種事,也很難說算是個什么事。但作為用Java的人,總是不免覺得別扭。把代碼寫的和文檔一樣又不是很難,也是應(yīng)該的。何必要這樣呢?