What happens if the load factor of a HashMap is greater than 1?

3k Views Asked by At

Default value of hashmap's load factor os 0.75f i.e it will re-hash the hash map once the 75% of capacity of hasmap is filled. What if I set the value of load factor greater than 1 for example lets say 2 (super(capacity+1, 2.0f, true);)

How it will work in sch case and how the hashing will work here?

2

There are 2 best solutions below

0
On BEST ANSWER

What if I set the value of load factor greater than 1 for example lets say 2 (super(capacity+1, 2.0f, true);)

You already have the answer;

... it will re-hash the hash map once the 200% of capacity of hashmap is filled.

The hashing works the same, it just uses a smaller capacity which impacts performance. If you make the initial capacity large enough the load factor never comes into play. The load factor only applies when the map is resized.

Note: the actual capacity is always a power of 2.

I suggest you try it.

BTW Changing the load factor can change the order the elements appear as there is less buckets. Trying printing out the Set or Map and comparing.

0
On

Java's HashMap uses closed addressing, so if multiple elements in the hash table all hash to the same location, Java just puts all of them in the same bucket in some auxiliary data structure. This allows the load factor to be arbitrarily high. This is different than, say, a linear probing hash table where the load factor cannot ever be more than one.