Java ArrayList - indexOf() Method
The java.util.ArrayList.indexOf() method returns index of the first occurrence of the specified element in this ArrayList. It returns -1 if element is not present in the ArrayList.
Syntax
public int indexOf(Object o)
Parameters
o |
Specify the element to search for in the ArrayList. |
Return Value
Returns the index of the first occurrence of the specified element in the ArrayList, or -1 if element is not present in the ArrayList.
Exception
NA.
Example:
In the example below, the java.util.ArrayList.indexOf() method is used to find the index of first occurrence of the specified element in the ArrayList MyList.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a ArrayList ArrayList<Integer> MyList = new ArrayList<Integer>(); //populating ArrayList MyList.add(10); MyList.add(30); MyList.add(20); MyList.add(50); MyList.add(30); System.out.print("30 appeared first time at index=" + MyList.indexOf(30)); } }
The output of the above code will be:
30 appeared first time at index=1
❮ Java.util - ArrayList