When an ArrayList resizes itself, how many elements does it add?
Java's ArrayList dynamically expands itself when it needs t开发者_如何学JAVAo. How many elements does it add when the expansion happens?
And does it copy the old array into the new one, or does it somehow link the two together?
Have a look at the source code:
int newCapacity = (oldCapacity * 3)/2 + 1;
The exact factor differs by implementation, gnu uses a factor of 2. It doesn't matter much, it's just trading memory for speed.
It copies all the elements into a new array.
It creates a new array of double some multiple of the size, and copies the elements over. (I'm not sure if the actual multiplier is specified per the Java standard.)
Now the natural question is, why? Why not just add, say, five elements every time?
It's to make things faster: You add n elements for free, and on element n + 1, you have to copy over the n previous elements into the array of size 2n. So the cost of copying those n elements gets distributed ("amortized") over themselves (since you previously added them for free), and so on average, the cost of adding each element was n/n, or about 1 operation per element.
(See this link for some more discussion on this topic.)
Strictly speaking, the exact resizing behavior is not specified in the spec/JavaDoc:
The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
This implies that the internal array can't be resized by adding a constant number, but that some multiplication has to be involved. As maartinus has pointed out the Sun JDK and OpenJDK multiply the size by 1.5 (roughly).
精彩评论