List.indexOf()
Finds the position of an element in a list.
Available since: Java 1.2
Syntax
int indexOf(Object o)
int lastIndexOf(Object o)Parameters
| Parameter | Type | Description |
|---|---|---|
| o | Object | The element to look for. |
Return value
intThe index of the first (or last) occurrence, or `-1` if the element is absent.
Examples
The first and the last occurrence:
void main() {
List<String> letters = List.of("a", "b", "c", "b");
IO.println(letters.indexOf("b"));
IO.println(letters.lastIndexOf("b"));
IO.println(letters.indexOf("z"));
}Output:
1
3
-1Notes
A result of -1 means the element is absent — check it before using the index. Elements are compared with equals().
See also
- List.contains() — Checks whether a list contains an element.
- List.get() — Returns the list element at an index.
- List.remove() — Removes a list element by index or by value.
Related recipes
In the tutorial
- Lists: List and ArrayList — Lists in Java: ArrayList, adding, reading and removing elements, unmodifiable List.of lists and lists of numbers.