Junior — Middle
How is the ability to dynamically expand an array in ArrayList implemented and why can it hold an arbitrary number of elements?
sobes.tech AI
Answer from AI
ArrayList in Java is implemented based on an array that initially has a fixed size. When the number of elements exceeds the current size of the internal array, it is expanded — a new, larger array is created, and all elements are copied into it.
This allows inserting an arbitrary number of elements, as ArrayList dynamically increases its capacity as needed.
An example of simplified expansion logic:
private void ensureCapacity(int minCapacity) {
if (minCapacity > elementData.length) {
int newCapacity = elementData.length * 3 / 2 + 1;
if (newCapacity < minCapacity) {
newCapacity = minCapacity;
}
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
Thus, when adding elements, ensureCapacity is called, and if the current array is full, a new, larger array is created, ensuring dynamic expansion.