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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With