Q:

Java program to find index of an element from an ArrayList

belongs to collection: Java ArrayList Programs

0

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"

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java program to replace element within the ArrayLi... >>
<< Java program to search an element from an ArrayLis...