Back to Blog
Java

java arraylist lastindexof: Syntax and Behavior

java arraylist lastindexof: Learn how to use ArrayList.lastIndexOf() to find the last occurrence of an element, handle null values, and understand its O(n) linear scan...

ArrayListJava CollectionsList APIIndex LookupAlgorithm Complexity
Illustration of a magnifying glass scanning an ArrayList from the bottom to find the last matching element.

When you need to find the position of an element in a java.util.ArrayList, the indexOf method gives you the first match. But when duplicate values are present and you need the position of the most recent occurrence, java arraylist lastindexof is the method to use. It returns the index of the last matching element, or -1 if the list contains no such element.

The lastIndexOf Method and Its Return Value

The lastIndexOf method is defined on the List interface and implemented by ArrayList. Its signature is public int lastIndexOf(Object o). It compares the specified object with the elements in the list using the equals method of the elements. The method returns the index of the last occurrence of the specified element in this list, or -1 if the list does not contain the element. The returned index is an int, so it can be used directly for list operations, but you must always check for the -1 sentinel value before using it to index into the list.

Basic Usage and a Minimal Example

Consider a list of strings where a value appears multiple times. The following example demonstrates how to use lastIndexOf to find the final position of a duplicate.

import java.util.ArrayList; import java.util.List; public class LastIndexExample { public static void main(String[] args) { List<String> items = new ArrayList<>(); items.add("apple"); items.add("banana"); items.add("apple"); items.add("cherry"); items.add("apple"); int lastIndex = items.lastIndexOf("apple"); System.out.println("Last index of 'apple': " + lastIndex); // Output: 4 } }

In this example, "apple" appears at indices 0, 2, and 4. The lastIndexOf call scans the list from the end and returns 4. If the element were not present, it would return -1.

How lastIndexOf Handles null Elements

Unlike some other collection types, ArrayList permits null elements. The lastIndexOf method handles null gracefully. If you pass null as the argument, it will find the last null in the list.

List<String> withNulls = new ArrayList<>(); withNulls.add("a"); withNulls.add(null); withNulls.add("b"); withNulls.add(null); int nullIndex = withNulls.lastIndexOf(null); System.out.println("Last null index: " + nullIndex); // Output: 3

This behavior is consistent with indexOf, which also supports null. This is particularly useful when cleaning up data that may contain missing values.

Runtime Cost and Why It Is a Linear Scan

The implementation of lastIndexOf in ArrayList performs a linear scan starting from the last index (size - 1) and iterating backwards to index 0. This means the time complexity is O(n), where n is the size of the list. There is no internal index or hash map that tracks element positions. Every call to lastIndexOf will traverse the list from the end until it finds a match or exhausts the list. If you are performing frequent reverse lookups on a large list, this repeated O(n) cost can become a bottleneck. In such cases, maintaining a separate Map that maps values to their latest index can reduce lookup time to O(1), at the cost of extra memory and the complexity of keeping the map synchronized with list modifications.

Choosing Between indexOf and lastIndexOf

The choice between these two methods depends entirely on which occurrence you need. The following table summarizes their key differences.

CriterionindexOflastIndexOf
Search directionStarts from index 0, moves forwardStarts from size - 1, moves backward
Return valueFirst matching indexLast matching index
Typical use caseFinding the first occurrenceFinding the most recent occurrence
ComplexityO(n)O(n)

Use indexOf when you need the earliest position, such as when processing a queue in order. Use lastIndexOf when you need the most recent position, such as when finding the latest log entry for a specific user ID in a chronological list.

Common Pitfalls When Using the Returned Index

A frequent mistake is using the returned index without checking for -1. Attempting to call list.get(-1) will throw an IndexOutOfBoundsException. Always guard against the -1 case when the element may be absent. Another pitfall arises when the list is modified after you obtain the index. If you insert or remove elements before that index, the stored index becomes stale and may point to a different element. Finally, remember that lastIndexOf relies on the equals method. If you are storing custom objects and have not overridden equals, the method will fall back to reference equality, which may not produce the expected result when comparing distinct objects with identical field values.

java arraylist lastindexof: Syntax and Behavior | RYUSLOG DEV