Defining Java constants using bit-shift notation

I was looking at the class source code java.util.HashMapand noticed that the explicit no-arg constructor expects two constants:

/**
 * 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);
}

But when I looked at the constant DEFAULT_INITIAL_CAPACITY, I found that it was defined as follows:

/**
 * The default initial capacity - MUST be a power of two.
 */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

I have never seen this type of construct used in any product that I worked on, and could not find any results in the Java Language Specification or through Google. So I looked at the byte code, but I found that using 16vs 1 << 4provided identical output, which means that (at least in my minimalist case) the compiler will convert the latter to decimal notation. The bytecode of both versions includes the definition:

javap -c -verbose /---/myClass.class
----
public static final int i;
flags: ACC_PUBLIC, ACC_STATIC, ACC_FINAL
ConstantValue: int 16

.

+4
2

, , , - 2 ^ 4.

, , .

+3

: , 1, 1 << N, .

HashMap , ( ).

, , :

, ( , )

, , . 16 1<<4 , , , .

+3

Source: https://habr.com/ru/post/1569851/


All Articles