Best HashMap initial capacity while indexing a List

前端 未结 6 573
小蘑菇
小蘑菇 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:23

    What you're doing is fine. In this way you're sure that the hash map has at least enough capacity for the initial values. If you have more information regarding the usage patterns of the hash map (example: is it updated frequently? are many new elements added frequently?), you might want to set a bigger initial capacity (for instance, list.size() * 2), but never lower. Use a profiler to determine if the initial capacity is falling short too soon.

    UPDATE

    Thanks to @PaulBellora for suggesting that the initial capacity should be set to (int)Math.ceil(list.size() / loadFactor) (typically, the default load factor is 0.75) in order to avoid an initial resize.

提交回复
热议问题