CKTIS / Java
List.indexOf(Object) — index of the first match
Find the first occurrence of an element in a Java list. The result is a zero-based index, or `-1` when no element matches.
Version: Java SE 21
Syntax
int indexOf(Object o)
int index = list.indexOf(value);List.indexOf(Object) is a method on java.util.List<E> that takes the object to find, not an index. It leaves the list unchanged. It returns the lowest matching index as an int: the first element is at index 0, and no match gives -1.
Position i matches when Objects.equals(o, list.get(i)) is true. Two null arguments compare equal; for a non-null o, comparison uses its equals method. A match therefore does not require both references to point to the same object. If the list disallows null, searching for null can return -1 or throw NullPointerException. For an incompatible argument type, the implementation can return -1 or throw ClassCastException.
Check index >= 0 before passing the result to get: -1 is not a valid index. With duplicates, use lastIndexOf(Object) if you need the final match. If you only need to know whether the element is present, use contains(Object), which returns a boolean.
In many implementations the search is linear and may need to examine every element in the list.
Examples
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> colors = List.of("red", "blue", "red");
String target = new String("red");
int first = colors.indexOf(target);
System.out.println(first);
System.out.println(colors.lastIndexOf(target));
System.out.println(colors.indexOf("green"));
if (first >= 0) {
System.out.println(colors.get(first));
}
}
}Result
0 2 -1 red
`new String("red")` deliberately creates a separate object with the same text. The first and last matches are at `0` and `2`; `"green"` gives `-1`. The condition guards the call to `get`, which prints `red`.
Related lessons
- Java · Lesson 54 · Basic · Version: 2