The lastIndexOf()
method is a valuable operation available in the Java ArrayList
class. It allows you to find the last occurrence index of a specified element in the list. This is especially useful when dealing with lists containing duplicate elements and you need to locate the most recent position where a value appears.
What Is the lastIndexOf() Method in ArrayList?
- The lastIndexOf() method returns the index of the last occurrence of a specified element in the list.
- If the element is not present, it returns -1.
- The search checks elements from the end of the list to the start, using the
equals()
method for comparison. - It supports all types: primitives (as wrappers), strings, objects, and also
null
values.
Syntax
public int lastIndexOf(Object o)
Where:
o
is the element for which to find the last occurrence.
Parameters
Parameter | Description |
---|---|
o | The element whose last index you want to find |
- The method accepts
null
and will return the last index ofnull
if present.
Return Value
- Returns the index of the last occurrence of the specified element.
- Returns -1 if the element is not found in the list.
Exceptions
- The method does not throw any checked exceptions.
- No error for invalid input; simply returns -1 if not found.
How Does lastIndexOf() Work Internally?
- lastIndexOf() loops through the ArrayList in reverse order (from the last item to the first).
- Each element is compared with the argument using
equals()
. - The index of the first matching occurrence found (going backward) is returned.
- If no match is found, -1 is returned.
- Time complexity is O(n), where
n
is the size of the list.
Examples of the lastIndexOf() Method
1. Find the Last Occurrence of a String
import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> animals = new ArrayList<>(); animals.add("Dog"); animals.add("Cat"); animals.add("Dog"); animals.add("Rabbit"); animals.add("Dog"); int lastDog = animals.lastIndexOf("Dog"); System.out.println("Last 'Dog' is at index: " + lastDog); // Output: 4 } }
Output:
Last 'Dog' is at index: 4
2. Element Not Present in the List
import java.util.ArrayList; public class Demo { public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(10); numbers.add(20); numbers.add(30); int lastIndex = numbers.lastIndexOf(40); // Not in list System.out.println("Index of 40: " + lastIndex); // Output: -1 } }
3. Using lastIndexOf() with Custom Objects
import java.util.ArrayList; class Book { String title; Book(String title) { this.title = title; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Book)) return false; Book other = (Book) obj; return this.title.equals(other.title); } } public class Example { public static void main(String[] args) { ArrayList<Book> books = new ArrayList<>(); books.add(new Book("Java")); books.add(new Book("Python")); books.add(new Book("Java")); Book search = new Book("Java"); int index = books.lastIndexOf(search); System.out.println("Last 'Java' book index: " + index); // Output: 2 } }
4. Find Last Occurrence of null
import java.util.ArrayList; public class NullTest { public static void main(String[] args) { ArrayList<String> items = new ArrayList<>(); items.add("Pen"); items.add(null); items.add("Book"); items.add(null); System.out.println(items.lastIndexOf(null)); // Output: 3 } }
Important Notes
- Last Occurrence: If the element appears multiple times,
lastIndexOf()
returns only the last occurrence’s index. - Not Found: Returns -1 if the element does not exist in the list.
- Custom Objects: For correct results, custom classes should override the
equals()
method. - null Support: Handles searching for
null
values as well. - Difference with indexOf():
indexOf()
searches from the beginning,lastIndexOf()
from the end.
Summary
Aspect | Details |
---|---|
Method Purpose | Find the index of last occurrence of an element |
Syntax | list.lastIndexOf(Object o) |
Return Value | Index if found, -1 if not found |
Supports null? | Yes |
Throws Exception | None (for standard use) |
Case Sensitivity | Yes (e.g., "Dog" ≠ "dog" ) |
Time Complexity | O(n) (linear search, from the end) |
Typical Use Cases | Locating last duplicate, reverse searches |
Typical Use Cases
- Finding the position of the last duplicate in a list.
- Determining the last input or action of a specific value in a sequence.
- Reverse searches in ordered data or history logs.