【发布时间】:2012-05-24 20:09:48
【问题描述】:
我正在阅读 java.util.HashMap 中 HashMap 的实现。初始容量、最大容量等都是2的幂。
从 java.util.HashMap 复制的部分声明
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 16;
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The table, resized as necessary. Length MUST Always be a power of two.
*/
transient Entry[] table;
cmets 建议尺寸必须是 2 的幂。为什么二的力量如此重要?
【问题讨论】:
-
某些类型的哈希表使用计算的哈希值的位模式中的一些位作为数组的索引。在这种情况下,大小必须是 2 的幂。看来 HashMap 的实现就是这样工作的。