How do you find the element of a LinkedList in Java?

JavaObject Oriented ProgrammingProgramming

indexOf() method of List can be used to get the location of an element in the list.

int indexOf(Object o)

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.

Parameters

  • o − Element to search for.

Returns

The index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

Throws

  • ClassCastException − If the type of the specified element is incompatible with this list (optional).

  • NullPointerException − If the specified element is null and this list does not permit null elements (optional).

Example

Following is the example showing the usage of indexOf() method −

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {
      List<String> list = new ArrayList<>();
      list.add("Zara");
      list.add("Mahnaz");
      list.add("Ayan");
      System.out.println("List: " + list);
      String student = "Ayan";
      String missingStudent = "Aman";
      System.out.println("Ayan is present at: " + list.indexOf(student));
      System.out.println("Aman index: " + list.indexOf(missingStudent));
   }
}

Output

This will produce the following result −

List: [Zara, Mahnaz, Ayan]
Ayan is present at: 2
Aman index: -1
raja
Updated on 10-May-2022 08:10:23

Advertisements