Java Utility Library

Java ArrayList - lastIndexOf() Method



The java.util.ArrayList.lastIndexOf() method returns index of the last occurrence of the specified element in this ArrayList. It returns -1 if element is not present in the ArrayList.

Syntax

public int lastIndexOf(Object obj)

Parameters

obj Specify the element to search for in the ArrayList.

Return Value

Returns the index of the last occurrence of the specified element in the ArrayList, or -1 if element is not present in the ArrayList.

Exception

NA.

Example:

In the example below, the java.util.ArrayList.lastIndexOf() method is used to find the index of last occurrence of the specified element in the ArrayList MyList.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a ArrayList
    ArrayList<Integer> MyList = new ArrayList<Integer>();

    //populating ArrayList
    MyList.add(10);
    MyList.add(30);
    MyList.add(20);
    MyList.add(50);
    MyList.add(30);

    System.out.print("30 appeared last time at index=" + MyList.lastIndexOf(30)); 
  }
}

The output of the above code will be:

30 appeared last time at index=4

❮ Java.util - ArrayList