I have a list (List
) and I want to index its objects by their ids using a map (HashMap
). I always use list.si
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.