Junior — Middle
How to add an element to an ArrayList when its current size reaches maximum capacity?
sobes.tech AI
Answer from AI
In ArrayList, when adding an element, if the current size reaches the maximum capacity of the internal array, the array is expanded.
The mechanism works as follows:
- A new larger array is created (usually the current size multiplied by 1.5 or 2).
- The contents of the old array are copied into the new one.
- The new element is added to the expanded array.
This allows ArrayList to dynamically increase capacity as needed, while maintaining fast index access.
Here's an example of how the expansion is implemented:
int newCapacity = oldCapacity + (oldCapacity >> 1); // increase by 50%
E[] newArray = (E[]) new Object[newCapacity];
System.arraycopy(oldArray, 0, newArray, 0, oldCapacity);
array = newArray;
Thus, adding an element when the array is full triggers memory reallocation and copying data into a new array with increased capacity.