Best HashMap initial capacity while indexing a List

前端 未结 6 566
小蘑菇
小蘑菇 2021-01-31 16:46

I have a list (List list) and I want to index its objects by their ids using a map (HashMap map). I always use list.si

6条回答
  •  一生所求
    2021-01-31 17:29

    According to the reference documentation of java.util.HashMap:

    The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as 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.

    This means, if you know in advance, how many entries the HashMap should store, you can prevent rehashing by choosing an appropriate initial capacity and load factor. However:

    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 get and put).

提交回复
热议问题