Search code examples
javahashmapopen-source

Why are numbers hard-coded like 1<<4 in HashMap.java class


I was looking at the source code of HashMap.java at this link.

I came across a couple of pieces of code like this:

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

and

static final int MAXIMUM_CAPACITY = 1 << 30;

My question is, if these values have to be hard-coded, why not hard-code the evaluated values instead of these left-shift operators?


Solution

  • It's to emphasize the fact that they're powers of 2, must be powers of 2 and are an easy way to write powers of 2.

    From the source code on 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;