What is the LinkedList.indexOf method in Java?
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.
Syntax
public int indexOf(Object obj);
Parameter
obj: The element to be searched in the list as an argument.
Return value
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.
Code
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"));}}
Explanation
In the above code:
- In line number 1, we import the
LinkedListclass.
import java.util.LinkedList;
- In line number 4, we create a
LinkedListobject with the namelist.
LinkedList<String> list = new LinkedList<>();
- From line number 5 to 7, we use the
addmethod of thelistobject to add three elements ("1","2","3") to the list.
list.add("1");
list.add("2");
list.add("1");
- In line number 10, we use the
indexOfmethod of thelistobject to get the index of the first occurrence of the element"1". The element"1"is present at two indices:0and2. We get0as result since that is the first occurrence.
list.indexOf("1"); // 0
- In line number 11, we use the
indexOfmethod of thelistobject to get the index of the first occurrence of the element"2". The element"2"is present only at index1, so it is returned.
list.indexOf("2"); // 1
- In line number 12, we use the
indexOfmethod of thelistobject to get the index of the first occurrence of the element"3". The element"3"is not present in the list, so-1is returned.
list.indexOf("3"); // -1