What will happen if the initial capacity as power of 2 in Hashmap.

In general, the number of buckets should be prime is so that the hash values are well distributed and will have less collisions. In case of HashMap, the capacity is always a power-of-two. hashmap bucket

In HashMap, if the size is specified and is not a power-of-2, it will be incremented to power-of-2 to create the internal array.

In order to convert the hash code to index, we divide it by the capacity and the remainder would be the index. There seems to be a Bug in versions from JDK1.4 on-wards where integer and modulus operation are much slower than its earlier versions. If the capacity of array is in power-of-two, the hash code can be easily converted to the index based on a simple AND operation and this seems to be more efficient as compared to modulus operation:

index = hashCode & (array length-1)

This might be the reason why the array capacity always has to be a power-of-two.


You can read more from below links



You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *