Java LinkedList indexOf() lastIndexOf() Methods Tutorial

In this section, we will learn what the LinkedList indexOf() and lastIndexOf() methods are and how to use them in Java.

What is Java LinkedList indexOf() Method?

Java LinkedList indexOf() method is used to get the index number of the first occurrence of a specific element in LinkedList object.

Java indexOf() Method Syntax:

public int indexOf(Object o)

indexOf() Method Parameters:

The method takes one argument and that is the element we want to find its index number in the target LinkedList object.

indexOf() Method Return Value:

The return value of this method is the index number of the specified element.

Note: we get the value -1 if the target list doesn’t have the argument.

indexOf() Method Exceptions:

The method does not throw an exception.

Example: using LinkedList indexOf() method

import java.util.LinkedList; 
class Main{
    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<>();
        list.add("John");
        list.add("Omid");
        list.add("Jack");
        list.add("Ellen");
        list.add("Elon");

        System.out.println(list.indexOf("Omid"));
        System.out.println(list.indexOf("Mike"));
    }
}

Output:

1

-1

What is Java LinkedList lastIndexOf() Method?

The Java LinkedList lastIndexOf() method is used to get the index number of the last occurrence of a specific element in a LinkedList object.

Note: another way to consider this method is to think that this method starts from the tail of a list and searches its way toward the head of that list.

Java lastIndexOf() Method Syntax:

public int lastIndexOf(Object o)

lastIndexOf() Method Parameters:

The method takes one argument and that is the element we want to find the index number of its last occurrence in a LinkedList object.

lastIndexOf() Method Return Value:

The return value of this method is of type integer and is equal to the index number of last occurrence of the argument we’ve set for the method.

Note: if there’s no such element in the target list, the return value of this method will be -1.

lastIndexOf() Method Exceptions:

The method does not throw an exception.

Example: using LinkedList lastIndexOf() method

import java.util.LinkedList; 
class Main{
    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<>();
        list.add("John");
        list.add("Omid");
        list.add("Jack");
        list.add("Ellen");
        list.add("Elon");

        System.out.println(list.lastIndexOf("Ellen"));
        System.out.println(list.lastIndexOf("Mike"));
    }
}

Output:

3

-1
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies