Home » Java programs » Java ArrayList programs

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







Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.