Why ArrayList grows at a rate of 1.5, but for Hashmap it's 2?

后端 未结 7 1158
暖寄归人
暖寄归人 2020-12-28 17:28

As per Sun Java Implementation, during expansion, ArrayList grows to 3/2 it\'s initial capacity whereas for HashMap the expansion rate is double. What is reason behind this?

7条回答
  •  情话喂你
    2020-12-28 18:08

    The expensive part at increasing the capacity of an ArrayList is copying the content of the backing array a new (larger) one.

    For the HashMap, it is creating a new backing array and putting all map entries in the new array. And, the higher the capacity, the lower the risk of collisions. This is more expensive and explains, why the expansion factor is higher. The reason for 1.5 vs. 2.0? I consider this as "best practise" or "good tradeoff".

提交回复
热议问题