ADVERTISEMENT
ADVERTISEMENT

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 »





ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.