ArrayList: how does the size increase?

crazyTechie picture crazyTechie · Dec 15, 2010 · Viewed 126.8k times · Source

I have a basic question on Java ArrayList.

When ArrayList is declared and initialized using the default constructor, memory space for 10 elements is created. Now, when I add an 11th element, what happens? Will new memory space be created with 20 (or more) element capacity (this requires copying elements from 1st memory location to new location) OR some thing else?

I checked here. But I didn't find an answer.

Please share the knowledge. Thanks.

Answer

T.J. Crowder picture T.J. Crowder · Dec 15, 2010

A new array is created and the contents of the old one are copied over. That's all you know at the API level. Quoting from the docs (my emphasis):

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

In terms of how it actually happens with a specific implementation of ArrayList (such as Sun's), in their case you can see the gory details in the source. But of course, relying on the details of a specific implementation isn't usually a good idea...