7

When I read the Java source code of HashMap.class,

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

why does Java use 1<<4, not 16?

Boann
  • 48,794
  • 16
  • 117
  • 146
Smallnine
  • 165
  • 7
  • 2
    Ask this guy ~ http://hg.openjdk.java.net/jdk8/jdk8/jdk/rev/2e3cc7f599ca – Phil Mar 20 '19 at 05:14
  • 6
    You may yourself write code with readability in mind. For example, one may want to declare a bunch of time period in second, and write `5025` seconds as `1 * 60 * 60 + 23 * 60 + 45` so that you know it is `1:23:45` once you look at it. These simple expressions should be optimized by compiler anyway so don't worry for performance hit. – Ricky Mo Mar 20 '19 at 05:23
  • @RickyMo since `1 << 4` is a compile-time constant, the compiler *must* treat it the same way as if you had written `16`. The same applies to your `1 * 60 * 60 + 23 * 60 + 45` example. Even at the places within the code where `DEFAULT_INITIAL_CAPACITY` is used, the compiler must treat it the same way as the literal value `16`. Besides not having any performance impact, it implies that you can use descriptive expressions and named constants at places where only compile-time constants are allowed, like annotation values or `case` labels of `switch` statements. – Holger Mar 20 '19 at 12:12

2 Answers2

13

Because it's clearly stated in the Java documentation that default initial capacity must be a power of two. If we were to see just any other integer instead of the bitwise operator, that wouldn't illustrate the limitation so well.

Thus by using a left shift operator, it is letting every developer know that it is there for us to notice a point which one should know, be it while modifying or using the HashMap class.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
abdev
  • 597
  • 4
  • 17
  • 2
    plus one, this makes it clear that it's `2 pow 4`, power of two being burned inside a `HashMap`; for example this is how a bucket is chosen - `(n - 1) & hash`, only possible when power of two buckets. – Eugene Mar 20 '19 at 10:10
6

It provides more readability and understanding of how you arrived at a certain number to begin with. Consider the below example

final int red = 1;
final int blue = 1 << 1;
final int magenta = red | blue; // 3

Each bit in the above numbers represent a primary color, and from the code you could easily figure out why I chose 3 for magenta. It wouldn't have been easier for the reader if you directly set the value 3 in the declaration.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Samuel Robert
  • 10,106
  • 7
  • 39
  • 60