Skip to content

WebDevHubs

  • Home
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • Java
  • Selenium
  • PHP
  • Python
  • Programs
  • Toggle search form

Java ArrayList lastIndexOf() Method

Posted on July 23, 2025July 23, 2025 By Admin No Comments on Java ArrayList lastIndexOf() Method

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

ParameterDescription
oThe element whose last index you want to find
  • The method accepts null and will return the last index of null 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

AspectDetails
Method PurposeFind the index of last occurrence of an element
Syntaxlist.lastIndexOf(Object o)
Return ValueIndex if found, -1 if not found
Supports null?Yes
Throws ExceptionNone (for standard use)
Case SensitivityYes (e.g., "Dog" ≠ "dog")
Time ComplexityO(n) (linear search, from the end)
Typical Use CasesLocating 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.
Java Tags:Java-ArrayList, Java-ArrayList-Method, Java-Collections

Post navigation

Previous Post: Java ArrayList iterator() Method
Next Post: Java ArrayList listIterator() Method

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Java ArrayList
  • Java ArrayList Methods
  • Java ArrayList add() Method
  • Java ArrayList addAll() Method
  • Java ArrayList clear() Method
  • Java ArrayList clone() Method
  • Java ArrayList contains() Method
  • Java ArrayList ensureCapacity() Method
  • Java ArrayList forEach() Method
  • Java ArrayList get() Method
  • Java ArrayList indexOf() Method
  • Java ArrayList isEmpty() Method
  • Java ArrayList iterator() Method
  • Java ArrayList lastIndexOf() Method
  • Java ArrayList listIterator() Method
  • Java ArrayList remove() Method
  • Java ArrayList removeAll() Method
  • Java ArrayList removeIf() Method
  • Java ArrayList replaceAll() Method
  • Java ArrayList retainAll() Method
  • Java ArrayList set() Method
  • Java ArrayList size() Method
  • Java ArrayList sort() Method
  • Java ArrayList spliterator() Method
  • Java ArrayList subList() Method
  • Java ArrayList toArray() Method
  • Java ArrayList trimToSize() Method

Recent Posts

  • Java ArrayList trimToSize() Method
  • Java ArrayList toArray() Method
  • Java ArrayList subList() Method
  • Java ArrayList spliterator() Method
  • Java ArrayList sort() Method

Recent Comments

No comments to show.

Important Pages

  • About Us
  • Contact Us
  • Terms of Use
  • Privacy Policy

Web Development

  • HTML
  • CSS
  • JavaScript
  • PHP

Programming Languages

  • Java
  • Python
  • PHP
  • Programs

Others

  • Selenium
  • Lodash
  • Java ArrayList
  • JavaScript Array Methods

Copyright © 2025 WebDevHubs.

Powered by PressBook Green WordPress theme