问题描述
比较JDK 1.6中的HashMap
和Hashtable
源代码,我在HashMap中看到了以下代码:
Comparing the HashMap
and Hashtable
source code in JDK 1.6, I saw the below code inside HashMap:
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 16;
int capacity = 1;
while (capacity < initialCapacity)
capacity <<= 1;
但是,在Hashtable中,我看到了:
However, in Hashtable, I saw this:
table = new Entry[initialCapacity];
public Hashtable() {
this(11, 0.75f);
}
所以我的问题是:为什么HashMap需要2的幂作为初始容量,而Hashtable选择11作为默认初始容量?我认为这与Hashtable是线程安全的并且不允许空键或值无关.
So my question is:Why does HashMap require a power of 2 as the initial capacity, while Hashtable chooses 11 as the default initial capacity?I assume this has nothing to do with the thing that Hashtable is thread-safe and does not allow null key or values.
推荐答案
下面的文章详细介绍了此问题: HashMap需要更好的hashCode()-JDK 1.4第II部分.
The following article addresses this question in some detail: HashMap requires a better hashCode() - JDK 1.4 Part II.
根据该文章,转换为2的幂次幂的主要原因是位掩码比整数除法快.这并非没有不良后果,其中一位原始作者对此进行了解释:
According to that article, the main reason to move to power-of-two sizes was that bit masking is faster than integer division. This is not without adverse consequences, which are explained by one of the original authors:
这篇关于为什么Hashtable 11的initialCapacity为HashMap,而HashMap中的DEFAULT_INITIAL_CAPACITY为16并要求2的幂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!