Java LinkedList indexOf() Method

Java LinkedList Java LinkedList


indexOf()The method is, in Java,LinkedLista commonly used method provided by the class, used to find the first occurrence position of the specified element in the linked list. This method belongs to thejava.util.LinkedListclass, and is inherited from thejava.util.AbstractListclass.

Method Syntax:

public int indexOf(Object o)

Return Value:

  • Returns the index of the first occurrence of the specified element in the linked list (counting from 0)
  • Returns -1 if the linked list does not contain the element

Parameter Description

Parameter Type Description
o Object The element to be found in the linked list

Notes

  1. The parameter can be of any object type, includingnull
  2. When searching, theequals()method is used for element comparison
  3. If the linked list contains multiple identical elements, only the index of the first matching item is returned

Usage Example

Basic Example

Example

import java.util.LinkedList;

public class LinkedListIndexOfExample {
    public static void main(String[] args) {
        // Create a LinkedList
        LinkedList<String> fruits = new LinkedList<>();
       
        // Add elements
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");
        fruits.add("Banana"); // Duplicate element
       
        // Find the element index
        System.out.println("Index of 'Banana': " + fruits.indexOf("Banana")); // Output: 1
        System.out.println("Index of 'Grape': " + fruits.indexOf("Grape"));   // Output: -1
        System.out.println("Index of 'Orange': " + fruits.indexOf("Orange")); // Output: 2
    }
}

Handling null Elements

Example

import java.util.LinkedList;

public class NullIndexOfExample {
    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<>();
        list.add("A");
        list.add(null);
        list.add("B");
       
        System.out.println("Index of null: " + list.indexOf(null)); // Output: 1
    }
}

Implementation Principle

Underlying Implementation

LinkedListofindexOf()The method finds the element by traversing the linked list nodes:

  1. Start traversing from the first node (head node) of the linked list
  2. For each node, use theequals()method to compare elements
  3. When the first matching node is found, return the current index
  4. If still not found after traversing all nodes, return -1

Time Complexity

  • Average time complexity: O(n)
  • Worst-case time complexity: O(n)

BecauseLinkedListit is implemented based on a linked list, requiring sequential search from the beginning, and cannot be randomly accessed like an array.


Comparison with Related Methods

indexOf() vs lastIndexOf()

Method Description Search Direction
indexOf() Returns the position of the first occurrence of the element From beginning to end
lastIndexOf() Returns the position of the last occurrence of the element From end to beginning

indexOf() vs contains()

Method Return Value Purpose
indexOf() int (index position) Use when you need to know the position of the element
contains() boolean Use when you only need to know whether the element exists

In fact,contains()the method internally callsindexOf() >= 0to implement it.


Practical Application Scenarios

Scenario 1: Check if an Element Exists

Example

LinkedList<String> usernames = new LinkedList<>();
// ... Add username

String input = "admin";
if (usernames.indexOf(input) != -1) {
    System.out.println("Username already exists");
} else {
    System.out.println("You can register");
}

Scenario 2: Get the Element Position for Subsequent Operations

Example

LinkedList<Task> taskList = new LinkedList<>();
// ... Add tasks

int index = taskList.indexOf(importantTask);
if (index != -1) {
    // Insert a new task before an important task
    taskList.add(index, newUrgentTask);
}

Scenario 3: Data Deduplication

Example

LinkedList<String> listWithDuplicates = new LinkedList<>();
// ... Add data that may contain duplicates

LinkedList<String> uniqueList = new LinkedList<>();
for (String item : listWithDuplicates) {
    if (uniqueList.indexOf(item) == -1) {
        uniqueList.add(item);
    }
}

Notes

  1. Performance considerations: For frequent lookup operations,ArrayListofindexOf()is usuallyLinkedListfaster
  2. Element comparison: Ensure that the objects stored in theLinkedListcorrectly implement theequals()method
  3. Concurrent modification: If the linked list is modified during iteration, it may throwConcurrentModificationException
  4. null handling: You can search fornullelements, but be aware ofNullPointerExceptionrisks

Summary

LinkedListofindexOf()The method is a practical lookup tool that:

  • Simple and easy to use, just pass in the element to find
  • Returns the index of the first occurrence of the element
  • Returns -1 when not found
  • Applicable to various object types, includingnull

Understanding and mastering this method can help you handle data lookup needs in linked lists more effectively.

Java LinkedList Java LinkedList

Other Extensions