Example of the ArrayList method indexOf()

The indexOf() of the ArrayList class is used to find the position of the first occurrence of a specific element in the ArrayList in Java.

public int indexOf(Object o): This method returns the index of the first occurrence of the object o, otherwise -1 if the specified item does not exist in the list.

import java.util.ArrayList; 

public class ArrayListIndexOfFirst{

public static void main(String[] args) {

// Create an ArrayList< String>
ArrayList< String> arraylist = new ArrayList< String> ();

//add strings to ArrayList
arraylist.add("e1");
arraylist.add("e2");
arraylist.add("e1");
arraylist.add("e3");
arraylist.add("e4");

System.out.println("first occurrence of e1: "+arraylist.indexOf("e1"));
System.out.println("first occurrence of e3: "+arraylist.indexOf("e3"));
}
}
Runtime:

first occurrence of e1:0
first occurrence of e3:3
References:
Java.util.ArrayList.indexOf() Method