indexof list java

w‮uttual.ww‬ri.com
indexof list java

In Java, the indexOf() method is a method of the List interface that returns the index of the first occurrence of a specified element in the list, or -1 if the element is not found in the list.

Here is an example of how to use the indexOf() method to find the index of an element in a List:

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

public class IndexOfExample {
    public static void main(String[] args) {
        List<String> myList = new ArrayList<>();
        myList.add("apple");
        myList.add("banana");
        myList.add("cherry");

        // Find the index of "banana" in the list
        int index = myList.indexOf("banana");
        System.out.println("The index of 'banana' is: " + index);

        // Find the index of "orange" in the list (which is not in the list)
        index = myList.indexOf("orange");
        System.out.println("The index of 'orange' is: " + index);
    }
}

Output:

The index of 'banana' is: 1
The index of 'orange' is: -1

Note that the indexOf() method uses the equals() method to compare elements, so if you are using a custom class as the element type, you will need to override the equals() method in order for the indexOf() method to work correctly.

You can also use the lastIndexOf() method to find the index of the last occurrence of a specified element in the list.

Created Time:2017-11-01 22:29:51  Author:lautturi