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

The class java.util.Map has a static member DEFAULT_INITIAL_CAPACITY which is assigned a int value calculated by the bitwise operation 1<<4 which means 16.

My question is why they assigned the value like this. What is the advantage of assigning the value using a bitwise operator instead of directly assigning an int value?

Boann
  • 48,794
  • 16
  • 117
  • 146
Girdhar Singh Rathore
  • 5,030
  • 7
  • 49
  • 67
  • 4
    To make it clear in code as well, in addition to the javadoc, that it must be a power of two. – guido Jun 26 '16 at 09:19

2 Answers2

4

The Javadoc says the default initial capacity "MUST be a power of two".

By writing the assignment as a left shift, it encourages future developers to ask themselves "why did they write it like that?" and thus read the comments, while also making it easier for the value to be changed to a different power of two.

ᴇʟᴇvᴀтᴇ
  • 12,285
  • 4
  • 43
  • 66
2

Here is my guess:

The capacity of a java HashMap is always supposed to be a power of two (for reasons beyond the scope of this question). Therefore the default initial capacity must be a power of two. While 16 is a power of two, 1 << 4 illustrates this restriction clearly to anyone who may want to modify the code.

ILMTitan
  • 10,751
  • 3
  • 30
  • 46