开发者

ArrayList capacity increment equation

In the JDK 1.7 into the ArrayList.java the method ensureCapacity increments the array capacity using the following expression: int newCapacity = oldCapacity + (oldCapacity >> 1) so it seems that the new capacity will be almost the 50% more than the old.

However in many books is said that the capac开发者_JAVA技巧ity is doubled... so the books aren't updated or I don't understand well?


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.


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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜