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

Java 8Object Oriented ProgrammingProgramming

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 occurance 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"));
raja
Published on 18-Jan-2019 05:23:17
Advertisements