Java ArrayList lastIndexOf() method
Syntax and Examples

Introduction

The lastIndexOf() method in Java's ArrayList lets you find the *last* occurrence of a specific object within the list. Think of it like searching for something and knowing you want to find the most recent time it appeared, not just any time.

Syntax

public int lastIndexOf(Object o)

Parameters

Parameter Description
o The object to search for within the ArrayList. Can be null.

Return Value

The method returns the index of the last occurrence of the specified element in this list, or -1 if it is not found.

Examples

Example 1: Finding a String

This example demonstrates how to find the last occurrence of a specific string within an ArrayList.

import java.util.ArrayList;

public class LastIndexOfExample {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>(
                Arrays.asList("Alice", "Bob", "Charlie", "Alice", "Ram")
        );

        int lastIndex = names.lastIndexOf("Alice");

        System.out.println("Last index of 'Alice': " + lastIndex);
    }
}
Last index of 'Alice': 3

Explanation: The ArrayList `names` contains the string “Alice” multiple times. The lastIndexOf() method returns 3, which is the index of the last occurrence of "Alice" in the list.

Example 2: Finding a Null Value

This example shows how to use lastIndexOf() when searching for a null value.

import java.util.ArrayList;
import java.util.Arrays;

public class LastIndexOfNullExample {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>(
                Arrays.asList("Alice", null, "Charlie", null, "Ram")
        );

        int lastIndex = names.lastIndexOf(null);

        System.out.println("Last index of null: " + lastIndex);
    }
}
Last index of null: 3

Explanation: The ArrayList `names` contains two null values. The lastIndexOf(null) method returns 3, which is the index of the last occurrence of null in the list.

Example 3: Object Not Found

This example demonstrates what happens when you try to find an object that isn't present in the ArrayList.

import java.util.ArrayList;
import java.util.Arrays;

public class LastIndexOfNotFoundExample {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>(
                Arrays.asList("Alice", "Bob", "Charlie")
        );

        int lastIndex = names.lastIndexOf("Eve");

        System.out.println("Last index of 'Eve': " + lastIndex);
    }
}
Last index of 'Eve': -1

Explanation: The ArrayList `names` does not contain the string "Eve". Therefore, lastIndexOf("Eve") returns -1 to indicate that the object was not found.