Java ArrayList lastIndexOf(Object o) Method example

In this tutorial we will learn how to use lastIndexOf(Object o) method of java.utilArrayList class. This method is used for finding the highest index of a particular element in the list.

Signature

public int lastIndexOf(Object o)

This method 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

The following example shows the usage of java.util.Arraylist.lastIndexOf(o) method.

import java.util.ArrayList;

public class ArrayListIndexOfExample
{
	public static void main(String[] args) { 
        // Create ArrayList al1 object
        ArrayList al1 = new ArrayList();
        
        //adding elements to al1
        al1.add("Element1");
        al1.add("Element2");
        al1.add("Element3");
        al1.add("Element4");
        al1.add("Element5");
        al1.add("Element6");
        al1.add("Element3");
        al1.add("Element7");
        
                
        //printing all the values of the ArrayList
        System.out.println("**Contents of List al1**");
        for(String val: al1)
        {
        	System.out.println(val);
        }

        //Retrieving the last index of the element "Element3"
        int index=al1.lastIndexOf("Element3");
        System.out.println("  Highest index of \"Element3\" is :"+index);
   }
}

Output

**Contents of List al1**
Element1
Element2
Element3
Element4
Element5
Element6
Element3
Element7
  Highest index of "Element3" is :6

Leave a Reply

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