Table of Contents
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:
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")); } } |
1 2 3 4 5 6 7 |
Index of Ankit: 1 ******************************* Index of John: 0 ******************************* Index of Arpit: -1 |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.