Nikunj Banka
Nikunj Banka

Reputation: 11365

How does java manage hashmap size allocations that would cause it to perform poorly?

For example if I allocate a Hashmap of size 100, and if 100 buckets get created then wouldn't the Hashmap perform poorly? (As performing modular hashing will not distribute the keys evenly in all of the 100 buckets)

How does java manage this problem? Does it randomly choose a prime near 100 to be the Hashmap size ?

Upvotes: 2

Views: 167

Answers (1)

Cephalopod
Cephalopod

Reputation: 15145

As you can you can see in the sources, it chooses the next biggest power of two (line 197 ff):

       // Find a power of 2 >= initialCapacity
       int capacity = 1;
       while (capacity < initialCapacity)
           capacity <<= 1;

       this.loadFactor = loadFactor;
       threshold = (int)(capacity * loadFactor);
       table = new Entry[capacity];

Upvotes: 1

Related Questions