Java List indexOf() example

In this guide, you will learn about the List indexOf() method in Java programming and how to use it with an example.

1. List indexOf() Method Overview

Definition:

The indexOf() method of the Java List interface returns the index of the first occurrence of the specified element in the list, or -1 if the list does not contain the element.

Syntax:

list.indexOf(Object o)

Parameters:

Object o - the element to search for.

Key Points:

- Returns the index of the first occurrence of the specified element.

- If the element is not found in the list, the method returns -1.

- It will return the index of the first occurrence in case there are multiple occurrences of the element in the list.

- Relies on the equals() method for element comparisons.

2. List indexOf() Method Example

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

public class ListIndexOfExample {
    public static void main(String[] args) {
        // Create a new ArrayList with some elements
        List<String> colors = new ArrayList<>();
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");
        colors.add("Green");

        // Find the index of "Green"
        int indexOfGreen = colors.indexOf("Green");
        System.out.println("Index of first occurrence of Green: " + indexOfGreen);  // Outputs: 1

        // Try to find an element not present in the list
        int indexOfPurple = colors.indexOf("Purple");
        System.out.println("Index of Purple: " + indexOfPurple);  // Outputs: -1
    }
}

Output:

Index of first occurrence of Green: 1
Index of Purple: -1

Explanation:

In the provided example:

1. We initiate an ArrayList of strings and add a few color names, including a duplicate of "Green".

2. Using the indexOf() method, we determine the index of the first occurrence of the color "Green".

3. Additionally, we demonstrate what happens when searching for an element that isn't present in the list, in this case, "Purple".

The indexOf() method is particularly useful when you want to determine the position of an element in a list. By returning -1 for non-existent items, it offers a clear indication of the absence of an element, making it an essential tool for list-based operations and comparisons.

Comments