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 ...
Boann source share