Java ArrayList.indexOf(): Finding the First Index of an Element

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().

1. Syntax, Method Signature & Equality Contract 🔝

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.

2. Basic Lookup & the -1 Sentinel Return Value 🔝

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

3. Duplicate Elements: indexOf() vs lastIndexOf() 🔝

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));  // 3

Terminal Output:

First index of 54: 1
Last index of 54:  3

4. Searching for null & Searching from a Starting Index 🔝

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);  // 3

Terminal Output:

First null index: 1
Next 'A' from index 1: 3

5. Finding All Occurrence Indices of a Value 🔝

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]

6. Comparison: Java List Index & Search Methods 🔝

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

7. Production Recipe: Find-and-Replace First Match 🔝

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]

8. Practical Recipe: Finding the Second Occurrence of an Element 🔝

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

9. Common Developer Pitfalls & Traps 🔝

Passing indexOf() Directly to get() or set() Without a != -1 Guard

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.

Redundant contains() + indexOf() Double Scan

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).

10. Complete Compilable Java Program 🔝

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!

11. Frequently Asked Questions (FAQ) 🔝

How can I tell if an element is unique in an ArrayList using indexOf()?

An element x occurs exactly once in list if and only if list.indexOf(x) != -1 && list.indexOf(x) == list.lastIndexOf(x).

Does ArrayList.indexOf(null) work?

Yes. When o == null, ArrayList.indexOf(null) scans for the first slot where elementData[i] == null without calling .equals().

Why does indexOf() return -1 for my custom object?

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.

What is the fastest way to find an element's index in a sorted ArrayList?

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).

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer