The indexOf
method of the LinkedList
class can be used to get the index of the first occurrence of the specified element in the linked list.
A linked list is a collection of linear data elements. Each element, or node, contains data and reference parts.
public int indexOf(Object obj);
obj
: The element to be searched in the list as an argument.This method returns the first index at which the specified element is present in the list.
If the element is not present in the list, then -1
is returned.
The code below demonstrates how to use the indexOf
method.
import java.util.LinkedList;class LinkedListIndexOfExample {public static void main( String args[] ) {LinkedList<String> list = new LinkedList<>();list.add("1");list.add("2");list.add("1");System.out.println("The list is " + list);System.out.println("First Index of element '1' is : " + list.indexOf("1"));System.out.println("First Index of element '2' is : " + list.indexOf("2"));System.out.println("First Index of element '3' is : " + list.indexOf("3"));}}
In the above code:
LinkedList
class.import java.util.LinkedList;
LinkedList
object with the name list
.LinkedList<String> list = new LinkedList<>();
add
method of the list
object to add three elements ("1","2","3"
) to the list.list.add("1");
list.add("2");
list.add("1");
indexOf
method of the list
object to get the index of the first occurrence of the element "1"
. The element "1"
is present at two indices: 0
and 2
. We get 0
as result since that is the first occurrence.list.indexOf("1"); // 0
indexOf
method of the list
object to get the index of the first occurrence of the element "2
". The element "2"
is present only at index 1
, so it is returned.list.indexOf("2"); // 1
indexOf
method of the list
object to get the index of the first occurrence of the element "3
". The element "3"
is not present in the list, so -1
is returned.list.indexOf("3"); // -1