Java program to find index of an element from an ArrayList

In this Java program, we are going to learn how to find an index of an element from an ArrayList? To find an index of an element using ArrayList.indexOf() method.
Submitted by IncludeHelp, on October 21, 2017

Given an ArrayList, and we have to find an index of an element from an ArrayList using Java program.

ArrayList.indexOf()

This method returns index of an element exists in the ArrayList, if element is not find, it returns "-1".

In this program, there are 5 elements "100", "200", "300", "400" and "500" and we are getting the index of "300"

Consider the program

import java.util.ArrayList;

public class SearchAnElement {
  public static void main(String[] args) {
    //ArrayList object 
    ArrayList arrList = new ArrayList();

    //adding elements in the list
    arrList.add("100");
    arrList.add("200");
    arrList.add("300");
    arrList.add("400");
    arrList.add("500");

    //searching element "300"
    int index = arrList.indexOf("300");
    if (index == -1)
      System.out.println("Element is not found in the list");
    else
      System.out.println("Element found @ index: " + index);
  }
}

Output

Element found @ index: 2

Java ArrayList Programs »





Comments and Discussions!










Copyright © 2023 www.includehelp.com. All rights reserved.