Java LinkedList indexOf() Method
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
- The parameter can be of any object type, including
null - When searching, the
equals()method is used for element comparison - If the linked list contains multiple identical elements, only the index of the first matching item is returned
Usage Example
Basic Example
Example
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
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:
- Start traversing from the first node (head node) of the linked list
- For each node, use the
equals()method to compare elements - When the first matching node is found, return the current index
- 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
// ... 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
// ... 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
// ... Add data that may contain duplicates
LinkedList<String> uniqueList = new LinkedList<>();
for (String item : listWithDuplicates) {
if (uniqueList.indexOf(item) == -1) {
uniqueList.add(item);
}
}
Notes
- Performance considerations: For frequent lookup operations,
ArrayListofindexOf()is usuallyLinkedListfaster - Element comparison: Ensure that the objects stored in the
LinkedListcorrectly implement theequals()method - Concurrent modification: If the linked list is modified during iteration, it may throw
ConcurrentModificationException - null handling: You can search for
nullelements, 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, including
null
Understanding and mastering this method can help you handle data lookup needs in linked lists more effectively.
Other Extensions
Java LinkedList