Java util ArrayList indexOf() Method Example

ArrayList Methods with Examples


Java ArrayList Examples


The java.util.ArrayList.indexOf(Object) method returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

Java util ArrayList indexOf() Method Example


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

// Check if an ArrayList contains a given element | contains()

// Find the index of the first occurrence of an element in an ArrayList | indexOf()

// Find the index of the last occurrence of an element in an ArrayList | lastIndexOf()

public class SearchElementsInArrayListExample {
    public static void main(String[] args) {
          // Creating an ArrayList of String using
         List<String> fruits = new ArrayList<>();
        // Adding new elements to the ArrayList
        fruits.add("Banana");
        fruits.add("Apple");
        fruits.add("mango");
        fruits.add("orange");
        fruits.add("Watermelon");
        fruits.add("Strawberry");
    
        // Find the index of the first occurrence of an element in an ArrayList
        System.out.println("indexOf \"Banana\": " + fruits.indexOf("Banana"));
        System.out.println("indexOf \"Apple\": " + fruits.indexOf("Apple"));
    }
}
Output:
indexOf "Banana": 0
indexOf "Apple": 1

Reference


Comments