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

后端 未结 7 1128
暖寄归人
暖寄归人 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 17:53

    I can't give you a reason why this is so (you'd have to ask Sun developers), but to see how this happens take a look at source:

    1. HashMap: Take a look at how HashMap resizes to new size (source line 799)

           resize(2 * table.length);
      
    2. ArrayList: source, line 183:

      int newCapacity = (oldCapacity * 3)/2 + 1;
      

    Update: I mistakenly linked to sources of Apache Harmony JDK - changed it to Sun's JDK.

提交回复
热议问题