Search an element of ArrayList in Java

Java 8Object Oriented ProgrammingProgramming

An element in an ArrayList can be searched 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("A");
      aList.add("B");
      aList.add("C");
      aList.add("D");
      aList.add("E");
      int index1 = aList.indexOf("C");
      int index2 = aList.indexOf("Z");
      if(index1 == -1)
         System.out.println("The element C is not in the ArrayList");
      else
         System.out.println("The element C is in the ArrayList at index " + index1);
      if(index2 == -1)
         System.out.println("The element Z is not in the ArrayList");
      else
         System.out.println("The element Z is in the ArrayList at index " + index2);
   }
}

Output

The element C is in the ArrayList at index 2
The element Z is not in the ArrayList

Now let us understand the above program.

The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. A code snippet which demonstrates this is as follows −

List aList = new ArrayList();
aList.add("A");
aList.add("B");
aList.add("C");
aList.add("D");
aList.add("E");

ArrayList.indexOf() returns the index of the first occurrence of “C” and “Z” that is stored in index1 and index2 respectively. Then an if statement is used to check if index1 is -1. If so, then C is not in ArrayList. A similar procedure is done with index2 and the results are printed. A code snippet which demonstrates this is as follows −

int index1 = aList.indexOf("C");
int index2 = aList.indexOf("Z");
if(index1 == -1)
   System.out.println("The element C is not in the ArrayList");
else
   System.out.println("The element C is in the ArrayList at index " + index1);
if(index2 == -1)
   System.out.println("The element Z is not in the ArrayList");
else
   System.out.println("The element Z is in the ArrayList at index " + index2);
raja
Published on 11-Jan-2019 11:18:29
Advertisements