Home »
Java programming language
Java LinkedList public int indexOf(Object o) method with Example
Java LinkedList public int indexOf(Object o) method: Here, we are going to learn about the public int indexOf(Object o) method of LinkedList class with its syntax and example.
Submitted by Preeti Jain, on June 22, 2019
LinkedList public int indexOf(Object o) method
- This method is available in package java.util.LinkedList.indexOf(Object o).
- This method is used to return the position or index of the first occurrence of the specified object of the linked list.
- In this method it returns -1 in two cases first will be if the element doesn't exist in the list then it returns -1 and second will be if list empty.
Syntax:
public int indexOf(Object o){
}
Parameter(s):
We can pass only one object as a parameter in the method of the linked list.
Return value:
The return type of this method is int type (i.e. number type ) that means this method returns the index of the first occurrence of the element after execution else returns -1.
Java program to demonstrate example of LinkedList indexOf(Object o) method
Case 1: Linked List with unique elements
import java.util.LinkedList;
public class LinkList {
public static void main(String[] args) {
LinkedList list = new LinkedList();
// use add() method to add elements in the list
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
// Current list Output
System.out.println("The Current list is:" + list);
// We will find the position of element 30 in the linked list
System.out.println("The position of element 30 in the list is:" + list.indexOf(30));
}
}
Output
D:\Programs>javac LinkList.java
D:\Programs>java LinkList
The Current list is:[10, 20, 30, 40, 50]
The position of element 30 in the list is:2
Case 2: Linked List with duplicate elements
import java.util.LinkedList;
public class LinkList {
public static void main(String[] args) {
LinkedList list = new LinkedList();
// use add() method to add elements in the list
list.add(10);
list.add(20);
list.add(30);
list.add(20);
list.add(40);
list.add(20);
list.add(50);
// Current list Output
System.out.println("The Current list is:" + list);
// We will find the position of element 20 in the linked list
//and here 20 comes thrice in a list so it will return
// index of first occurrence
System.out.println("The position of element 20 in the list is:" + list.indexOf(20));
}
}
Output
D:\Programs>javac LinkList.java
D:\Programs>java LinkList
The Current list is:[10, 20, 30, 20, 40, 20, 50]
The position of element 30 in the list is:1