Java Utility Library

Java LinkedList - indexOf() Method



The java.util.LinkedList.indexOf() method returns index of the first occurrence of the specified element in the list. It returns -1 if element is not present in the list.

Syntax

public int indexOf(Object obj)

Parameters

obj Specify the element to search for in the list.

Return Value

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

Exception

NA.

Example:

In the example below, the java.util.LinkedList.indexOf() method is used to find the index of first occurrence of 15 in the given list.

import java.util.*;

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

    //populating linkedlist
    MyList.add(10);
    MyList.add(15);
    MyList.add(30);
    MyList.add(15);
    MyList.add(40);

    System.out.print("15 appeared first time at index=" + MyList.indexOf(15)); 
  }
}

The output of the above code will be:

15 appeared first time at index=1

❮ Java.util - LinkedList