Java LinkedList indexOf(Object o) Method Example

In this tutorial we will learn the usage of indexOf(Object o) method of java.util.LinkedList class. This method is used for finding the index of a particular element in the list.


public int indexOf(Object o)

This method returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.


The following example shows the usage of java.util.LinkedList.indexOf(o) method.

import java.util.LinkedList;

public class IndexOfMethodLinkedListExample {
	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 3");
        list1.add("String 4");
        list1.add("String 3");
        list1.add("String 5");
        list1.add("String 3");
        //printing all the values of the LinkedList
        System.out.println("**Contents of List list1**");
        for(String val: list1)

        //Retrieving the index of the element "String 3"
        int index=list1.indexOf("String 3");
        System.out.println("\"String 3\" is present at the index :"+index);


**Contents of List list1**
String 1
String 2
String 3
String 4
String 3
String 5
String 3

"String 3" is present at the index :2

Leave a Reply

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