Java LinkedList lastIndexOf(Object o) Example

indexOf(Object o) method of java.util.LinkedList class helps us in getting the index of a particular element in the list.whereas lastIndexOf(Object o) 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.LinkedList.lastIndexOf(o) method.

import java.util.LinkedList;

public class LastIndexOfMethodLinkedListExample {
	public static void main(String args[])
	{
	// Create LinkedList object
        LinkedList list1 = new LinkedList();
        
        //adding elements to list1
        list1.add("String 1");
        list1.add("String 2");
        list1.add("String 4");
        list1.add("String 3");
        list1.add("String 4");
        list1.add("String 5");
        list1.add("String 3");
        list1.add("String 4");
                
        //printing all the values of the LinkedList
        System.out.println("**Contents of List list1**");
        for(String val: list1)
        {
        	System.out.println(val);
        }

        //Retrieving the highest index of the element "String 3"
        int index=list1.lastIndexOf("String 3");
        System.out.println("Highest index of \"String 3\" is :"+index);
	}
}

Output

**Contents of List list1**
String 1
String 2
String 4
String 3
String 4
String 5
String 3
String 4
Highest index of "String 3" is :6

Leave a Reply

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