ArrayList<E> · Java

remove(int) / remove(Object)

Removes by position or by value (first equal element); both shift the rest left.

public E remove(int index); public boolean remove(Object o)

Complexity

Best caseO(1) for the last index
Worst caseO(n)
Extra spaceO(1)

remove(int) shifts size − index − 1 references. remove(Object) also scans to find the element first.

Tested example

List<Integer> list = new ArrayList<>(List.of(5, 6, 7, 8));
int removed = list.remove(0); // remove(int index): shifts the rest left
assert removed == 5;
list.remove(Integer.valueOf(8)); // remove(Object): a different overload!
assert list.equals(List.of(6, 7));
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 / o
A position, or a value compared with equals().

Behaviour

Returns
remove(int): the removed element. remove(Object): whether something was removed.
Errors and preconditions
remove(int): IndexOutOfBoundsException for a bad index.
Changes
size decreases by 1; the vacated slot is nulled.
Memory and invalidation
Does not shrink the array.