Get Index of Elements in ArrayList Example

Each of the elements in an ArrayList has its own index number. The indexOf() returns the index of the first occurrence of the specified element, or -1 if the list does not contain the element. The lasindexOf() returns the index of the last occurrence of the specified element, or -1 if the list does not contain the element.

Get Index of Elements in ArrayList Example

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

public class GetIndexEx {

    public static void main(String[] args) {
        
        List<String> colours = new ArrayList<>();

        colours.add(0, "blue");
        colours.add(1, "orange");
        colours.add(2, "red");
        colours.add(3, "green");
        colours.add(4, "orange");
        
        int idx1 = colours.indexOf("orange");
        System.out.println(idx1);
        
        int idx2 = colours.lastIndexOf("orange");
        System.out.println(idx2);        
    }
}

Output

1
4



Comments