The ArrayList.lastIndexOf(Object o) method scans the list backward from the end (size() - 1 down to 0) and returns the 0-based index of the last occurrence of the specified element, or -1 if not found.
Related Search Operations: To find the first occurrence from the beginning of the list, use ArrayList.indexOf(). To remove the last matching occurrence of a duplicate value, pass the index returned by lastIndexOf() into ArrayList.remove(int index).
Declared in java.util.ArrayList<E>:
// Returns the 0-based index of the last occurrence of o, or -1 if not present
public int lastIndexOf(Object o)
| Element | Type / Value | Operational Rule |
|---|---|---|
o |
Object (nullable) |
Target element to match via Objects.equals(o, elementData[i]). |
| Return Value | int |
Highest index i in 0..size-1 where o occurs, or -1 if absent. |
| Scan Direction | Right-to-Left | Iterates downward from i = size - 1 to 0 in O(n) worst-case time. |
When every element added via add() is distinct, lastIndexOf() returns the exact same 0-based position as indexOf(), and returns -1 when the target is not present:
import java.util.ArrayList;
ArrayList<String> languages = new ArrayList<String>();
languages.add("Java");
languages.add("PHP");
languages.add("Python");
System.out.println(languages.lastIndexOf("PHP")); // 1
System.out.println(languages.lastIndexOf("Python")); // 2
System.out.println(languages.lastIndexOf("HTML")); // -1 (not present)Terminal Output:
1
2
-1
When an element appears multiple times (such as 54 at indices 1 and 3 below), lastIndexOf(54) stops at index 3 on its first step from the right, whereas indexOf(54) returns index 1:
ArrayList<Integer> marks = new ArrayList<Integer>();
marks.add(55);
marks.add(54);
marks.add(55);
marks.add(54);
System.out.println("Last index of 54: " + marks.lastIndexOf(54)); // 3
System.out.println("First index of 54: " + marks.indexOf(54)); // 1Terminal Output:
Last index of 54: 3
First index of 54: 1
To search backward starting from a specific upper index maxIdx (analogous to String.lastIndexOf(str, fromIndex)), call lastIndexOf() on list.subList(0, maxIdx + 1):
ArrayList<String> events = new ArrayList<>(Arrays.asList("OK", null, "RETRY", null, "DONE"));
System.out.println("Last null index: " + events.lastIndexOf(null)); // 3
// Search backward starting from index 2 (inclusive) using subList(0, 3)
int prevNull = events.subList(0, 3).lastIndexOf(null);
System.out.println("Last null at or before index 2: " + prevNull); // 1Terminal Output:
Last null index: 3
Last null at or before index 2: 1
An element occurs at most once in a list if its first index equals its last index:
ArrayList<String> tags = new ArrayList<>(Arrays.asList("java", "sql", "java", "xml"));
for (String t : Arrays.asList("java", "sql")) {
boolean isUnique = (tags.indexOf(t) != -1) && (tags.indexOf(t) == tags.lastIndexOf(t));
System.out.println("Tag '" + t + "' appears exactly once? " + isUnique);
}Terminal Output:
Tag 'java' appears exactly once? false
Tag 'sql' appears exactly once? true
How forward and reverse operations pair together on ArrayList:
| Goal | First Occurrence (Leftmost) | Last Occurrence (Rightmost) |
|---|---|---|
| Find 0-Based Index | list.indexOf(target) |
list.lastIndexOf(target) |
| Replace Match | list.set(list.indexOf(t), v) |
list.set(list.lastIndexOf(t), v) |
| Remove Match | list.remove(target) |
list.remove(list.lastIndexOf(t)) |
Because list.remove(Object) always removes the first matching element, use lastIndexOf() with remove(int index) to delete the last matching occurrence instead:
public class RemoveLastOccurrence {
public static <E> boolean removeLastMatch(ArrayList<E> list, E target) {
int lastIdx = list.lastIndexOf(target);
if (lastIdx != -1) {
list.remove(lastIdx); // Removes by index, not first object match!
return true;
}
return false;
}
public static void main(String[] args) {
ArrayList<String> steps = new ArrayList<>(Arrays.asList("INIT", "STEP", "VERIFY", "STEP"));
removeLastMatch(steps, "STEP");
System.out.println("After removing last STEP: " + steps);
}
}Terminal Output:
After removing last STEP: [INIT, STEP, VERIFY]
When events are appended chronologically, lastIndexOf("SAVE") finds the newest checkpoint in O(1) steps if it is near the tail:
public class LatestCheckpointFinder {
public static void main(String[] args) {
ArrayList<String> stages = new ArrayList<>(Arrays.asList("START", "SAVE", "EDIT", "SAVE", "EXIT"));
int lastSave = stages.lastIndexOf("SAVE");
System.out.println("Latest SAVE at index " + lastSave + " (steps since save: " + (stages.size() - 1 - lastSave) + ")");
}
}Terminal Output:
Latest SAVE at index 3 (steps since save: 1)
If x is not in the list, lastIndexOf(x) returns -1, and passing -1 to list.remove(-1) throws an IndexOutOfBoundsException! Always check if (lastIdx != -1) before calling remove(lastIdx).
Even though lastIndexOf() scans from right to left, the index it returns is still a standard 0-based index from the front of the list (not a 1-based offset from the tail).
Compile and run this verification class in any Java environment:
public class ArrayListLastIndexOfFullDemo {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "A", "C"));
if (list.lastIndexOf("A") == 2 && list.indexOf("A") == 0) {
System.out.println("Check 1 Passed: lastIndexOf(A) == 2 vs indexOf(A) == 0.");
}
if (list.lastIndexOf("Z") == -1) {
System.out.println("Check 2 Passed: Missing element returned -1.");
}
System.out.println("All ArrayList.lastIndexOf() verification checks passed!");
}
}Terminal Output:
Check 1 Passed: lastIndexOf(A) == 2 vs indexOf(A) == 0.
Check 2 Passed: Missing element returned -1.
All ArrayList.lastIndexOf() verification checks passed!
Yes. Because lastIndexOf() starts at size() - 1 and steps backward, finding an element that was recently appended at the tail takes only a few comparisons.
When isEmpty() is true (size == 0), the reverse loop starts at -1, does not execute, and immediately returns -1.
No. ArrayList.subList() returns a lightweight view over the same backing array and scans backward from index k - 1 down to 0 with zero array copying.
Like indexOf() and contains(), it calls o.equals(elementData[i]), so your custom class must override equals(Object).
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.