Get the index of first Occurrence of the element in the Arraylist

In this tutorial we will learn how to get index of Arraylist and to find out the index of particular element in a list, we used method indexOf(Object o);

public int indexOf(Object o); it return index of  a list .

import java.util.ArrayList;

public class Example {

public static void main(String[] args) {
   ArrayList<String> arrlist  = getArrayList();
}
public static ArrayList<String> getArrayList(){
            ArrayList<String> arrlist = new ArrayList<String>();
    //add method for String ArrayList
  arrlist.add("Item1");
  arrlist.add("Item2");
  arrlist.add("Item3");
  arrlist.add("Item4");
  arrlist.add("Item5");
 
  //index of First Occurrence of Element IN Arraylist
  System.out.println("ArrayList element Item1 of index 0 = "+ arrlist.indexOf("Item1"));
  System.out.println("ArrayList element Item2 of index 1 = "+ arrlist.indexOf("Item2"));
  System.out.println("ArrayList element Item3 of index 2 = "+ arrlist.indexOf("Item3"));
  System.out.println("ArrayList element Item4 of index 3 = "+ arrlist.indexOf("Item4"));
            return arrlist;
}
}

//result

ArrayList element Item1 of index 0 = 0
ArrayList element Item2 of index 1 = 1
ArrayList element Item3 of index 2 = 2
ArrayList element Item4 of index 3 = 3


EmoticonEmoticon