Get the index of a particular element in an ArrayList in Java


The index of a particular element in an ArrayList can be obtained by using the method java.util.ArrayList.indexOf(). This method returns the index of the first occurrence of the element that is specified. If the element is not available in the ArrayList, then this method returns -1.

A program that demonstrates this is given as follows.

Example

 Live Demo

import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      List aList = new ArrayList();
      aList.add("Orange");
      aList.add("Apple");
      aList.add("Peach");
      aList.add("Guava");
      aList.add("Mango");
      System.out.println("The index of the element Apple in ArrayList is: " +
      aList.indexOf("Apple"));
   }
}

Output

The output of the above program is as follows

The index of the element Apple in ArrayList is: 1

Now let us understand the above program.

The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. The method ArrayList.indexOf() is used to find the first index of element "Apple" and that is displayed. A code snippet which demonstrates this is as follows

List aList = new ArrayList();
aList.add("Orange");
aList.add("Apple");
aList.add("Peach");
aList.add("Guava");
aList.add("Mango");
System.out.println("The index of the element Apple in ArrayList is: " +
aList.indexOf("Apple"));

Updated on: 13-Sep-2023

25K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements