ArrayList<E> · Java
contains / indexOf
Linear search with equals().
public boolean contains(Object o); public int indexOf(Object o)
Complexity
| Best case | O(1) |
|---|---|
| Average | O(n) |
| Worst case | O(n) |
| Extra space | O(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;
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.