使用位移位表示法定义Java常量

使用位移位表示法定义Java常量,java,constants,bit-shift,jls,Java,Constants,Bit Shift,Jls,我正在浏览java.util.HashMap类的源代码,注意到显式无参数构造函数需要两个常量: /** * Constructs an empty <tt>HashMap</tt> with the default initial capacity * (16) and the default load factor (0.75). */ public HashMap() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LO

我正在浏览
java.util.HashMap
类的源代码,注意到显式无参数构造函数需要两个常量:

/**
 * Constructs an empty <tt>HashMap</tt> with the default initial capacity
 * (16) and the default load factor (0.75).
 */
public HashMap() {
    this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}

我从来没有在我开发的任何产品中使用过这种类型的构造,也没有在或通过谷歌搜索找到任何结果。所以我查看了字节码,但我发现使用
16
vs
1的必要性很简单:一个左移为1的常数,例如
1它是完全等效的,但这样写是为了更清楚地说明值的来源和计算方式——在本例中,它是打算为2^4

这本书可能是以任何一种方式写成的,作者们只是认为这会更加自我记录

/**
 * The default initial capacity - MUST be a power of two.
 */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
javap -c -verbose /---/myClass.class
----
public static final int i;
flags: ACC_PUBLIC, ACC_STATIC, ACC_FINAL
ConstantValue: int 16