tags:

views:

57

answers:

2

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 capacity is doubled... so the books aren't updated or I don't understand well?

+3  A: 

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.

Jon Skeet
How can be the JDK 7 compliant with the docs if it provides that expression? There the detail of how to calculate the growth policy is setted!
xdevel2000
Jon Freedman
@xdevel2000: Which bit of the JDK 7 implementation is incompatible with what I've quoted? Are you saying that adding an element *doesn't* have constant amortized time cost? The documentation gives *a* guarantee, but still leaves room for flexibility.
Jon Skeet
+2  A: 

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.

Jon Freedman