Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (4k points)

HashMap has two important properties: size and load factor. I went through the Java documentation and it says 0.75f is the initial load factor. But I can't find the actual use of it.

Can someone describe what are the different scenarios where we need to set load factor and what are some sample ideal values for different cases?

1 Answer

0 votes
by (46k points)

The documentation describes it comely well:

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including getting and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.

As with all production optimizations, it is a great idea to avoid optimizing something untimely (i.e. without dense data on where the bottlenecks happen).

Related questions

0 votes
1 answer
asked Jul 15, 2019 in Java by Nigam (4k points)
0 votes
1 answer
0 votes
1 answer
asked Aug 26, 2019 in Java by Krishna (2.6k points)
0 votes
1 answer
asked Aug 13, 2019 in Java by Nigam (4k points)
0 votes
1 answer

Browse Categories

...