ArrayList‘s indexOf method is used to find out first index of object in arraylist.
indexOf method takes object as argument and returns first occurrence of specified element.
Methods:
public int indexOf(Object o)
returns index of first occurrence of element in the ArrayList.
returns index of first occurrence of element in the ArrayList.
indexOf method return -1 if object is not present in the ArrayList
ArrayList indexOf Example:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.*;
class IndexOfArrayListMain {
/*
* @author : Arpit Mandliya
*/
public static void main(String[] args) {
ArrayList employeeNameList = new ArrayList();
employeeNameList.add("John");
employeeNameList.add("Ankit");
employeeNameList.add("Rohan");
employeeNameList.add("Amit");
System.out.println("Index of Ankit: "+employeeNameList.indexOf("Ankit"));
System.out.println("*******************************");
System.out.println("Index of John: "+employeeNameList.indexOf("John"));
System.out.println("*******************************");
// Arpit is not present in the list
System.out.println("Index of Arpit: "+employeeNameList.indexOf("Arpit"));
}
}
When you run above program, you will get below output
Index of Ankit: 1 ******************************* Index of John: 0 ******************************* Index of Arpit: -1