ArrayList<E> · Java

contains / indexOf

Linear search with equals().

public boolean contains(Object o); public int indexOf(Object o)

Complexity

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

Every element may need to be compared. Collections.binarySearch is O(log n) on a sorted ArrayList.

Tested example

List<String> colors = new ArrayList<>(List.of("red", "green", "blue"));
assert colors.contains("green"); // linear scan using equals()
assert colors.indexOf("blue") == 2;
assert colors.indexOf("purple") == -1;
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

o
The value (null allowed).

Behaviour

Returns
contains: a boolean. indexOf: the first index or -1.
Errors and preconditions
None.
Changes
Nothing.
Memory and invalidation
No allocation.

See it step by step: the Binary search: halving a sorted range lesson has an interactive 3D visualizer of the same mechanism.