ArrayList<E> · Java

add(int, E)

Inserts at a position and shifts later elements right.

public void add(int index, E element)

Complexity

Best caseO(1) at the end
Worst caseO(n) at the front
Extra spaceO(1) amortized

System.arraycopy moves size − index references.

Tested example

List<String> list = new ArrayList<>(List.of("a", "c", "d"));
list.add(1, "b"); // shifts "c" and "d" right
assert list.equals(List.of("a", "b", "c", "d"));
try {
    list.add(10, "x");
    throw new AssertionError("expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException expected) {
    // index must be in 0..size()
}
Runs in the test suite on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/test/java/dev/bekadan/dsa/collections/ArrayListExamples.java

Parameters

index
0 ≤ index ≤ size().
element
The element.

Behaviour

Returns
Nothing.
Errors and preconditions
IndexOutOfBoundsException if index < 0 or index > size().
Changes
size increases by 1.
Memory and invalidation
May grow the array.

See it step by step: the Dynamic arrays: capacity, resizing and amortized append lesson has an interactive 3D visualizer of the same mechanism.