Java ArrayList contains() Method Example

The contains() method of java.util.ArrayList class returns true if this list contains the specified element.

Signature

public boolean contains(Object o)

This method returns returns true if this list contains the specified element.

Example

The following example shows the usage of java.util.Arraylist.contains(o) method.

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 *