indexOf method takes object as argument and returns first occurrence of specified element.
Methods:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
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
1 2 3 4 5 6 7 |
Index of Ankit: 1 ******************************* Index of John: 0 ******************************* Index of Arpit: -1 |