HashMap initialization parameters (load / initialcapacity)

前端 未结 9 1474
[愿得一人]
[愿得一人] 2020-12-04 10:54

What values should I pass to create an efficient HashMap / HashMap based structures for N items?

In an ArrayList, the efficien

9条回答
  •  自闭症患者
    2020-12-04 11:22

    I ran some unit tests to see if these answers were correct and it turned out that using:

    (int) Math.ceil(requiredCapacity / loadFactor);
    

    as the initial capacity gives what you want for either a HashMap or a Hashtable. By "what you want" I mean that adding requiredCapacity elements to the map won't cause the array which it's wrapping to resize and the array won't be larger than required. Since the default load capacity is 0.75, initializing a HashMap like so works:

    ... = new HashMap((int) Math.ceil(requiredCapacity / 0.75));
    

    Since a HashSet is effectively just a wrapper for a HashMap, the same logic also applies there, i.e. you can construct a HashSet efficiently like this:

    .... = new HashSet((int) Math.ceil(requiredCapacity / 0.75));
    

    @Yuval Adam's answer is correct for all cases except where (requiredCapacity / 0.75) is a power of 2, in which case it allocates too much memory.
    @NotEdible's answer uses too much memory in many cases, as the HashMap's constructor itself deals with the issues that it want the maps array to have a size which is a power of 2.

提交回复
热议问题