1

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?

pri
  • 1,521
  • 2
  • 13
  • 26

3 Answers3

2

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;
Kayaman
  • 72,141
  • 5
  • 83
  • 121
1

Any good compiler will evaluate these expressions when compiling, and expression like these are easier for human to read and understand.

Roy Cai
  • 166
  • 1
  • 3
0

To show you which power of 2 in this situation.

ttt
  • 401
  • 2
  • 4
  • 17