Initial capacity setting mode of HashMap in Java

  • 2021-09-20 20:42:06
  • OfStack

Initial capacity setting of HashMap in Java

According to the recommendation in Alibaba Java Development Manual, set the known size when HashMap is initialized. If there are no more than 16, set it to the default size of 16:

When the collection is initialized, specify the initial value size of the collection.

Description:

HashMap is initialized with HashMap (int initialCapacity)

Positive example:

initialCapacity = (number of elements to be stored/load factor) + 1. Note that the load factor (that is, loader factor) defaults to 0.75, and if the initial value cannot be determined temporarily, set it to 16 (that is, the default value).

Counterexample:

HashMap needs to place 1024 elements. Because the initial capacity size is not set, the capacity is forced to expand seven times with the increasing number of elements. resize needs to rebuild hash table, which seriously affects the performance.

The answer to why the load factor is 0.75 can be found in the hash section of "Data Structure and Algorithm Analysis Java Language Description"

Specified initial value size and automatic expansion of Java HashMap

HashMap Specifies the initial value size

Specifies that the initial value size should be a power of 2.

If the specified initial value is not a power of 2, the capacity of the HashMap is a power of 2 greater than the specified initial value; If not specified, the capacity defaults to 16.

HashMap automatic expansion

When the number of key pairs of HashMap is greater than 75% of the capacity, the capacity of HashMap is doubled.


Related articles: