为什么数字硬编码为 HashMap.java class 中的 1<<4
Why are numbers hard-coded like 1<<4 in HashMap.java class
我在 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;
向您展示在这种情况下 2 的幂。
我在 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;
向您展示在这种情况下 2 的幂。