Junior — Middle
How does changing the size of ArrayList affect its capacity when adding new elements?
sobes.tech AI
Answer from AI
In Java, ArrayList uses an internal array to store elements. When adding new elements, if the current array is full, its size is increased — a new larger array is allocated, and the old elements are copied into it.
By default, when expansion is needed, the size of the internal array increases by approximately 50% of the current size. This balances between frequent copying and excessive memory consumption.
For example, if the current capacity was 10, it would increase to about 15 upon overflow.
This mechanism provides amortized efficiency for adding elements: although a single addition may trigger a costly copying operation, on average, adding is fast.
Example:
ArrayList<Integer> list = new ArrayList<>(2);
list.add(1);
list.add(2);
// When adding the third element, the internal array will expand
list.add(3);