Junior — Middle
How are elements stored in memory inside an ArrayList data structure?
sobes.tech AI
Answer from AI
In Java, ArrayList is implemented based on a dynamic array. Inside the ArrayList, elements are stored in a regular object array (Object[] elementData).
When you add elements, they are placed sequentially in this array. If the array fills up, the ArrayList creates a new array of larger size (usually increasing the current size by about 1.5 times), copies the old elements into it, and continues adding new ones.
Thus, elements are stored in a contiguous block of memory, which provides fast access by index (the get(index) operation is performed in constant time).
A simplified example of the internal structure:
private Object[] elementData;
private int size;
public void add(E e) {
ensureCapacity(size + 1);
elementData[size++] = e;
}
private void ensureCapacity(int minCapacity) {
if (minCapacity > elementData.length) {
int newCapacity = elementData.length + (elementData.length >> 1);
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
Thus, ArrayList provides dynamic array expansion and quick access to elements by index.