<分区>
我在 this link 查看 HashMap.java 的源代码.
我遇到过这样的几段代码:
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
和
static final int MAXIMUM_CAPACITY = 1 << 30;
我的问题是,如果必须对这些值进行硬编码,为什么不对评估值进行硬编码而不是对这些左移运算符进行硬编码?
<分区>
我在 this link 查看 HashMap.java 的源代码.
我遇到过这样的几段代码:
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
和
static final int MAXIMUM_CAPACITY = 1 << 30;
我的问题是,如果必须对这些值进行硬编码,为什么不对评估值进行硬编码而不是对这些左移运算符进行硬编码?
最佳答案
这是为了强调它们是 2 的幂,必须是 2 的幂并且是写 2 的幂的一种简单方法。
来自 Java 8 的源代码:
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 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;
关于java - 为什么数字在 HashMap.java 类中被硬编码为 1<<4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47386111/