ArrayList<E> · Java

get / set

Reads or replaces the element at a position.

public E get(int index); public E set(int index, E element)

Complexity

Best caseO(1)
Worst caseO(1)
Extra spaceO(1)

Direct array access; ArrayList implements the RandomAccess marker interface for exactly this reason.

Tested example

List<Integer> list = new ArrayList<>(List.of(1, 2, 3));
Integer previous = list.set(1, 20); // set returns the old element
assert previous == 2 && list.get(1) == 20;
try {
    list.get(3);
    throw new AssertionError("expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException expected) {
    // size(), not capacity, is the limit
}
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().

Behaviour

Returns
get: the element. set: the element previously at that position.
Errors and preconditions
IndexOutOfBoundsException if index < 0 or index ≥ size().
Changes
set replaces one element (not a structural modification: iterators stay valid).
Memory and invalidation
No allocation.