Question:
In Java…
- What is the initial size of an
ArrayList
? - Upon reaching the maximum size, when it "expands", is its size doubled?
Answer:
The initial capacity is 10 elements if not specified when creating the object. And when it peaks it is transparently reallocated (internal implementation) at twice the current capacity if the new capacity is enough for what it is going to do.
Doubling the capacity rather than allocating only the need is done to alleviate a problem similar toShlemiel the Painter's algorithm
where a small new addition to the ArrayList
already produce a new reallocation, making the operation slower and slower. The algorithm trades in an exaggerated amount of reallocations for possible wasted memory.
There's something talking about this on the OS here and here . Official documentation says initial capacity is 10, so this probably won't change, documented, becomes contract 🙂