Sobes.tech
Junior — Middle

How is the storage of elements inside an ArrayList implemented in Java?

sobes.tech AI

Answer from AI

In Java, the ArrayList structure is implemented based on a dynamic array. Inside the ArrayList, there is a regular array of objects (Object[] elementData), which increases in size as needed.

When a new element is added and the current array is full, a new, larger array is created (usually about 1.5 times larger), and all elements are copied into it. This allows efficient access to elements by index (operation in O(1)), but inserting or deleting elements in the middle of the list requires shifting elements.

An example of a simplified internal implementation:

private transient Object[] elementData;
private int size;

public boolean add(E e) {
    ensureCapacity(size + 1);
    elementData[size++] = e;
    return true;
}

private void ensureCapacity(int minCapacity) {
    if (minCapacity - elementData.length > 0) {
        grow(minCapacity);
    }
}

private void grow(int minCapacity) {
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + (oldCapacity >> 1); // increase by 50%
    if (newCapacity < minCapacity)
        newCapacity = minCapacity;
    elementData = Arrays.copyOf(elementData, newCapacity);
}
How is the storage of elements inside an ArrayList… - sobes.tech