ArrayList: how does the size increase?

arraylist, arrays, collections, java

Solution

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...

Problem

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 the `ArrayList` API documentation for Java 1.4.2. But I didn't find an answer. Please share the knowledge. Thanks. Edit: New links: - `ArrayList` in the Java 11 API documentation - Java(TM) 2 SDK, Standard Edition Documentation 1.4.2

Original source

Related problems