HashMap initialization parameters (load / initialcapacity)

前端 未结 9 1495
[愿得一人]
[愿得一人] 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:12

    The answer Yuval gave is only correct for Hashtable. HashMap uses power-of-two buckets, so for HashMap, Zarkonnen is actually correct. You can verify this from the source code:

      // Find a power of 2 >= initialCapacity
      int capacity = 1;
      while (capacity < initialCapacity)
      capacity <<= 1;
    

    So, although the load factor of 0.75f is still the same between Hashtable and HashMap, you should use an initial capacity n*2 where n is the number of elements you plan on storing in the HashMap. This will ensure the fastest get/put speeds.

提交回复
热议问题