Press "Enter" to skip to content

LinkedList indexOf() method with example in java

The indexOf(E element) method of LinkedList returns the first occurrence of the specified element in this linked list.

Syntax

int indexOf(E e)

Parameter

e is the element to find in this linked-list

Return Value

It returns the index of the first occurrence of the specified element

Program

import java.util.LinkedList;

public class LinkedListIndexOfExample {

	public static void main(String[] args) {

		LinkedList<Integer> oddNumbers = new LinkedList<>();
		oddNumbers.add(5);
		oddNumbers.add(7);
		oddNumbers.add(9);
		oddNumbers.add(11);

		System.out.println("Linked List elements: " + oddNumbers);
		System.out.println("Index of 7: " + oddNumbers.indexOf(7));

		System.out.println("Index of 11: " + oddNumbers.indexOf(11));

	}
}

Output

Linked List elements: [5, 7, 9, 11]
Index of 7: 1
Index of 11: 3

Be First to Comment

Leave a Reply

Your email address will not be published.