ArrayList capacity increment equation

前端 未结 4 821
一整个雨季
一整个雨季 2021-01-19 14:21

In the JDK 1.7 into the ArrayList.java the method ensureCapacity increments the array capacity using the following expression: int newCapacity = oldCapaci

相关标签:
4条回答
  • 2021-01-19 14:34

    In Java 6 newCapacity is calculated as => int newCapacity = (oldCapacity * 3)/2 + 1;

    In Java 7 newCapacity is calculated as => int newCapacity = oldCapacity + (oldCapacity >> 1)

    0 讨论(0)
  • 2021-01-19 14:50

    You're understanding is correct, newCapacity is 50% more than oldCapacity

    In Java 6 newCapacity is calculated as

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

    This is the beauty of an open source language such as Java, you can see the implementation - if it doesn't fit your requirements, you can implement your own.

    0 讨论(0)
  • 2021-01-19 14:50

    ArrayLists in Java increments the capacity by 50%. However, the vector class in Java, which functions similarly to ArrayLists but offers synchronization, will double capacity. This is likely where the confusion in your books came from.

    0 讨论(0)
  • 2021-01-19 14:58

    From the ArrayList javadoc:

    The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

    In other words, the books may be accurate for other implementations, but nothing's guaranteed - and the Java 7 source is still compliant with the docs, but shows the books to be overly specific.

    0 讨论(0)
提交回复
热议问题