Java ArrayList indexOf(Object o) Method Example

In this tutorial we will learn how to use indexOf(Object o) method of java.utilArrayList class. This method is used for finding the index of a particular element in the list.


public int indexOf(Object o) 

This method returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.


The following example shows the usage of java.util.Arraylist.indexOf(o) method.

import java.util.ArrayList;

public class ArrayListIndexOfExample
	public static void main(String[] args) { 
        // Create ArrayList al1 object
        ArrayList al1 = new ArrayList();
        //adding elements to al1
        al1.add("String 1");
        al1.add("String 2");
        al1.add("String 3");
        al1.add("String 4");
        //printing all the values of the ArrayList
        System.out.println("**Contents of List al1**");
        for(String val: al1)

        //Retrieving the index of the element "String 3"
        int index=al1.indexOf("String 3");
        System.out.println("\"String 3\" is present at the index :"+index);


**Contents of List al1**
String 1
String 2
String 3
String 4

"String 3" is present at the index :2

Leave a Reply

Your email address will not be published. Required fields are marked *