Java LinkedList indexOf() Method

The LinkedList.indexOf() method in Java is used to find the index of the first occurrence of a specified element in the LinkedList. This guide will cover the method’s usage, explain how it works, and provide examples to demonstrate its functionality.

Table of Contents

  1. Introduction
  2. indexOf Method Syntax
  3. Examples
    • Finding the Index of an Element
    • Handling Non-Existent Elements
  4. Conclusion

Introduction

The LinkedList.indexOf() method is a member of the LinkedList class in Java. It allows you to find the index of the first occurrence of a specified element within the list. This method is particularly useful for locating elements and understanding their position in the list.

indexOf Method Syntax

The syntax for the indexOf method is as follows:

public int indexOf(Object o)
  • o: The element to search for in the LinkedList.
  • Returns: The index of the first occurrence of the specified element, or -1 if the element is not found.

Examples

Finding the Index of an Element

The indexOf method can be used to find the index of the first occurrence of a specified element in a LinkedList.

Example

import java.util.LinkedList;

public class IndexOfExample {
    public static void main(String[] args) {
        // Creating a LinkedList of Strings
        LinkedList<String> list = new LinkedList<>();

        // Adding elements to the LinkedList
        list.add("Apple");
        list.add("Banana");
        list.add("Orange");
        list.add("Banana");

        // Finding the index of the first occurrence of "Banana"
        int index = list.indexOf("Banana");

        // Printing the index
        System.out.println("Index of 'Banana': " + index);
    }
}

Output:

Index of 'Banana': 1

Handling Non-Existent Elements

If the specified element is not found in the LinkedList, the indexOf method returns -1.

Example

import java.util.LinkedList;

public class IndexOfExample {
    public static void main(String[] args) {
        // Creating a LinkedList of Strings
        LinkedList<String> list = new LinkedList<>();

        // Adding elements to the LinkedList
        list.add("Apple");
        list.add("Banana");
        list.add("Orange");

        // Finding the index of a non-existent element "Grapes"
        int index = list.indexOf("Grapes");

        // Printing the result
        System.out.println("Index of 'Grapes': " + index);
    }
}

Output:

Index of 'Grapes': -1

Conclusion

The LinkedList.indexOf() method in Java provides a way to find the index of the first occurrence of a specified element in a LinkedList. By understanding how to use this method, you can efficiently locate elements and understand their position within your Java applications. Handling the potential return value of -1 ensures your code remains robust and can handle cases where the element is not found.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top