Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java use int i = 1<<4, not int i = 16? [duplicate]

Tags:

java

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?

like image 958
Smallnine Avatar asked Mar 20 '19 05:03

Smallnine


2 Answers

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.

like image 163
abdev Avatar answered Nov 09 '22 13:11

abdev


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.

like image 6
Samuel Robert Avatar answered Nov 09 '22 12:11

Samuel Robert