The ArrayList.indexOf(Object o) method scans the list from left to right and returns the 0-based index of the first occurrence of the specified element, or -1 if the list does not contain the element.
Related Search Operations: To find the last occurrence of a duplicate element, use ArrayList.lastIndexOf(). If you only need a boolean check without the index, use ArrayList.contains(). Once you have a valid index (>= 0), pass it to ArrayList.get() or ArrayList.set().
Declared in java.util.ArrayList<E>:
// Returns the 0-based index of the first occurrence of o, or -1 if not present
public int indexOf(Object o)
| Element | Type / Value | Operational Rule |
|---|---|---|
o |
Object (nullable) |
Element to search for; matched via Objects.equals(o, elementData[i]). |
| Return Value | int |
Lowest index i in 0..size-1 where a match is found, or -1 if absent. |
| Time Complexity | O(n) |
Sequential scan from index 0 upward; stops immediately at the first match. |
When an element added via add() is found, indexOf() returns its 0-based position. When searching for an item that does not exist (such as "HTML" below), it returns -1:
ArrayList<String> languages = new ArrayList<String>();
languages.add("Java");
languages.add("PHP");
languages.add("Python");
System.out.println(languages.indexOf("PHP")); // 1
System.out.println(languages.indexOf("Python")); // 2
System.out.println(languages.indexOf("HTML")); // -1 (not present)Terminal Output:
1
2
-1
If an element appears multiple times in an ArrayList, indexOf() always stops at and returns the first matching position. Use lastIndexOf() to find the final matching position:
ArrayList<Integer> marks = new ArrayList<>(Arrays.asList(55, 54, 55, 54));
System.out.println("First index of 54: " + marks.indexOf(54)); // 1
System.out.println("Last index of 54: " + marks.lastIndexOf(54)); // 3Terminal Output:
First index of 54: 1
Last index of 54: 3
Unlike String.indexOf(str, fromIndex), ArrayList does not have a 2-argument indexOf(o, fromIndex) overload. Instead, combine subList(fromIndex, size()) with .indexOf(o) and add fromIndex to the result:
ArrayList<String> tokens = new ArrayList<>(Arrays.asList("A", null, "B", "A"));
System.out.println("First null index: " + tokens.indexOf(null)); // 1
// Find "A" starting from index 1 using subList(1, size)
int rel = tokens.subList(1, tokens.size()).indexOf("A");
int absIndex = (rel == -1) ? -1 : 1 + rel;
System.out.println("Next 'A' from index 1: " + absIndex); // 3Terminal Output:
First null index: 1
Next 'A' from index 1: 3
To collect every index where a target value occurs, iterate from 0 to size() - 1 and compare with get(i):
ArrayList<String> logLevels = new ArrayList<>(Arrays.asList("INFO", "ERROR", "WARN", "ERROR"));
ArrayList<Integer> errorPositions = new ArrayList<>();
for (int i = 0; i < logLevels.size(); i++) {
if ("ERROR".equals(logLevels.get(i))) errorPositions.add(i);
}
System.out.println("All ERROR indices: " + errorPositions);Terminal Output:
All ERROR indices: [1, 3]
Contrasting the four standard ways to locate elements in an ArrayList:
| Method | Scan Direction | Return Value when Missing |
|---|---|---|
list.indexOf(o) |
Forward (0 → n-1) |
-1 |
list.lastIndexOf(o) |
Backward (n-1 → 0) |
-1 |
list.contains(o) |
Forward (0 → n-1) |
false |
Collections.binarySearch(list, o) |
Binary (O(log n)) |
-(insertionPoint) - 1 |
Combining indexOf(oldVal) with set(idx, newVal) safely updates the first occurrence of a value in place:
public class ReplaceFirstMatch {
public static <E> boolean replaceFirst(ArrayList<E> list, E oldVal, E newVal) {
int idx = list.indexOf(oldVal);
if (idx != -1) {
list.set(idx, newVal);
return true;
}
return false;
}
public static void main(String[] args) {
ArrayList<String> status = new ArrayList<>(Arrays.asList("PENDING", "ACTIVE", "PENDING"));
replaceFirst(status, "PENDING", "DONE");
System.out.println("Updated: " + status);
}
}Terminal Output:
Updated: [DONE, ACTIVE, PENDING]
Using indexOf() to locate the first match and subList() to locate the second match:
public class SecondOccurrenceFinder {
public static <E> int secondIndexOf(ArrayList<E> list, E target) {
int first = list.indexOf(target);
if (first == -1 || first + 1 >= list.size()) return -1;
int rel = list.subList(first + 1, list.size()).indexOf(target);
return (rel == -1) ? -1 : (first + 1 + rel);
}
public static void main(String[] args) {
ArrayList<String> items = new ArrayList<>(Arrays.asList("X", "Y", "X", "Z"));
System.out.println("2nd index of X: " + secondIndexOf(items, "X"));
}
}Terminal Output:
2nd index of X: 2
Writing list.set(list.indexOf(target), newVal) directly will crash with IndexOutOfBoundsException: Index -1 out of bounds whenever target is not in the list! Always store int idx = list.indexOf(target); and check if (idx != -1) first.
Avoid writing if (list.contains(x)) { int i = list.indexOf(x); }. Because contains(x) simply calls indexOf(x) >= 0, calling both scans the entire array twice! Call int i = list.indexOf(x); once and check if (i >= 0).
Compile and run this verification class in any Java environment:
public class ArrayListIndexOfFullDemo {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>(Arrays.asList("Java", "PHP", "Java"));
if (list.indexOf("Java") == 0 && list.lastIndexOf("Java") == 2) {
System.out.println("Check 1 Passed: First and last index of duplicate verified.");
}
if (list.indexOf("Ruby") == -1) {
System.out.println("Check 2 Passed: Missing element returned -1.");
}
System.out.println("All ArrayList.indexOf() verification checks passed!");
}
}Terminal Output:
Check 1 Passed: First and last index of duplicate verified.
Check 2 Passed: Missing element returned -1.
All ArrayList.indexOf() verification checks passed!
An element x occurs exactly once in list if and only if list.indexOf(x) != -1 && list.indexOf(x) == list.lastIndexOf(x).
Yes. When o == null, ArrayList.indexOf(null) scans for the first slot where elementData[i] == null without calling .equals().
If your custom class does not override public boolean equals(Object o), indexOf() falls back to Object.equals() (memory reference identity ==), which returns false for distinct instances with identical fields.
If the list is sorted in ascending order, use Collections.binarySearch(list, key) to locate an element in O(log n) time instead of O(n).
ArrayList.ArrayList.ArrayList methods.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.