Sobes.tech
Junior — Middle

How does the internal array in ArrayList behave when it needs to increase its size?

sobes.tech AI

Answer from AI

The internal array in ArrayList in Java, when it needs to increase in size, creates a new array larger in size, usually about 1.5 times the current size. Then all elements from the old array are copied into the new one, after which the reference to the internal array is updated. This allows ArrayList to dynamically expand when new elements are added, but the resize operation is time-consuming due to data copying.

This is approximately how the size increase occurs:

ArrayList<Integer> list = new ArrayList<>();
// When adding elements, if the internal array is full,
// a new array with increased capacity is created and data is copied.
list.add(1);
list.add(2);
// ...

This behavior is hidden from the user, but it is important to consider when working with large volumes of data to minimize the number of expansions (for example, by setting an initial capacity).