×

Java Programs

Java Practice

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? By IncludeHelp Last updated : December 31, 2023

Problem statement

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

Finding index of an element from an ArrayList

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

Java program to find index of an element from an ArrayList

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

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

The output of the above example is:

Element found @ index: 2

Java ArrayList Programs »

Comments and Discussions!

Load comments ↻





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