Java ArrayList indexOf example

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.


public int indexOf(Object o)
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();
  System.out.println("Index of Ankit: "+employeeNameList.indexOf("Ankit"));
  System.out.println("Index of John: "+employeeNameList.indexOf("John"));
 // 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

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus


Java tutorial for beginners Copyright © 2012