Why use 1 << 4 instead of 16?

The OpenJDK code for java.util.HashMap includes the following line:

 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 

Why is 1 << 4 used here and not 16 ? I am curious.

+7
source share
3 answers

To emphasize that the number is a power of two, not a completely arbitrary choice. Thus, developers experiment with different numbers in order to change them to other numbers in the template (for example, 1 << 3 or 1 << 5 , not 25 ) so that they do not break the code. There is a comment just above :

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

The capacity of any java.util.HashMap always equal to the power of two. It is designed in this way because it allows you to use the fast bitwise AND operation to wrap each key hash in a range of table capacities, as you can see in table access methods :

 final Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n; K k; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { /// <-- bitwise 'AND' here ... 
+17
source

I can’t read the developer's mind, but we do things to indicate the relationship between the numbers.

Compare this:

int day = 86400;

against

int day = 60 * 60 * 24; // 86400

The second example clearly shows the relationship between numbers, and Java is smart enough to compile this as a constant.

+8
source

I think the reason is that the developer can very easily change the value (according to JavaDoc '/ * The default initial capacity MUST be two. * /'), For example, to 1 << 5 or 1 << 3 and he does not need to make any calculations.

0
source

All Articles