ArrayList contains[] method checks if the list has the specified element or not. Technically, it returns true only when the list contains at least one element where the following condition is met. [o == null ? e== null : e.equals[o]], where e is each element in the list. You can also check the presence of the null element and custom object in the list.
Syntax:
public boolean contains[Object obj]Parameter obj is the element whose presence needs to be checked.
Returns true if the ArrayList has the specified element; otherwise, it returns false.
ArrayList contains[] Example
Lets look at the program with an Integer type.
import java.util.ArrayList; public class Demo1 { public static void main[String[] args] { ArrayList numbers = new ArrayList[]; numbers.add[12]; numbers.add[43]; numbers.add[54]; numbers.add[23]; numbers.add[89]; numbers.add[76]; System.out.println["ArrayList elements : " + numbers]; System.out.println["Does the list have 54 : " + numbers.contains[54]]; System.out.println["Does the list have 45 : " + numbers.contains[45]]; } }Output:
ArrayList elements : [12, 43, 54, 23, 89, 76] Does the list have 54 : true Does the list have 45 : falsecontains[] with String type
Lets look at the program to see contains[Element e] with String element type. The time complexity of this method is O[n] where n is the number of elements in the list.
Output:
ArrayList element: [Coding, Testing, Deploying, Support] Does the list have Testing: true Does the list have Maintainance: falseUsing contains with custom object
This program demonstrates how to check the ArrayList contains the custom object. It checks the presence by calling equals[] method of our object.
Thats all about the contains method. You can also go through our articles where we explain how to find the indexOf[] and lastIndexOf[] the element. Please share this article if you liked it.
Further References:
ArrayList Documentation