Sobes.tech
Junior — Middle

How does the size of ArrayList change when elements are added sequentially up to a certain number?

sobes.tech AI

Answer from AI

In Java, the ArrayList class implements a dynamic array that automatically increases its size when new elements are added, if the current capacity is filled.

Initially, ArrayList is created with a certain capacity (default is 10). When the number of elements reaches this capacity, the size of the internal array is increased. In the standard implementation, the size increases by approximately 50% of the current size (i.e., new capacity = old capacity + old capacity / 2).

This balances the costs of copying data and memory usage.

Example:

ArrayList<Integer> list = new ArrayList<>();
// Adding elements, when size reaches 10, capacity will increase to about 15
for (int i = 0; i < 20; i++) {
    list.add(i);
}
How does the size of ArrayList change when elements… - sobes.tech