if ((n & -n) == n) // i.e., n is a power of 2
// rest of the code
Run Code Online (Sandbox Code Playgroud)
为什么是这样?
可能重复:
Java HashMap默认初始容量
我正在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.
*/ …Run Code Online (Sandbox Code Playgroud) 如果您知道,请说明原因.我用Google搜索,但没有找到解释清楚的答案.
当你hashCode是负面时,是否使桶的指数为正?
我知道默认情况下HashMap的大小为16,我们还可以为其提供其他值。如果我用0.8f的加载因子将大小初始化为5,然后向其中添加第五个元素,该怎么办?它会增长到10或16?一旦阈值突破发生(非2的幂),它会跳到2的幂吗?