Search for a element ArrayList in Java

In this example we will learn how to search if a element is present in the ArrayList or not. We will use the contains() and indexOf() methods to achieve this.

import java.util.ArrayList;

public class ArrayListSearchExample {

	public static void main(String args[]) 
	{
		// Creating an empty array list
		ArrayList al = new ArrayList();
		
		//Adding elements to the arraylist
		al.add("Element1");
		al.add("Element3");
		al.add("Element2");
		al.add("Element4");
		
		if(al.contains("Element2"))
		{
			System.out.println("Element2 is present at the index "+al.indexOf("Element2"));
		}
		else
		{
			System.out.println("Element2 is not present in the list");
		}
	}
}

Output

Element2 is present at the index 2

Leave a Reply

Your email address will not be published. Required fields are marked *