What does the method lastIndexOf(obj o) do in java?


The lastIndexOf(Object) method of the class java.util.ArrayList returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.

Example

import java.util.ArrayList;

public class ArrayListDemo {
   public static void main(String[] args) {
      ArrayList<String> arrlist = new ArrayList<String>(5);
      arrlist.add("G");
      arrlist.add("E");
      arrlist.add("F");
      arrlist.add("M");
      arrlist.add("E");
      System.out.println("Size of list: " + arrlist.size());
      for (String value : arrlist) {
         System.out.println("Value = " + value);
      }
      int retval=arrlist.lastIndexOf("E");
      System.out.println("The last occurrence of E is at index " + retval);
   }
}

Output

Size of list: 5
Value = G
Value = E
Value = F
Value = M
Value = E
The last occurrence of E is at index 4

Updated on: 20-Feb-2020

40 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements