How to Check if ArrayList Contains Element in Java
In Java, you can check if an
ArrayList contains a specific element by using the contains() method. This method returns true if the element is found and false otherwise.Syntax
The contains() method is called on an ArrayList object and takes one argument: the element you want to check for. It returns a boolean value.
arrayList.contains(element): Checks ifelementis in the list.- Returns
trueif found,falseif not.
java
boolean contains(Object element)Example
This example shows how to create an ArrayList of strings and check if it contains certain elements using the contains() method.
java
import java.util.ArrayList; public class CheckContainsExample { public static void main(String[] args) { ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); System.out.println(fruits.contains("Banana")); // true System.out.println(fruits.contains("Mango")); // false } }
Output
true
false
Common Pitfalls
One common mistake is checking for an element that is null without handling it properly, which can cause unexpected results. Also, contains() uses the equals() method to compare elements, so if you use custom objects, make sure to override equals() and hashCode() methods correctly.
Another pitfall is confusing contains() with checking the index or using == for comparison, which checks reference equality, not content equality.
java
import java.util.ArrayList; class Person { String name; Person(String name) { this.name = name; } // Without overriding equals, contains may fail } public class PitfallExample { public static void main(String[] args) { ArrayList<Person> people = new ArrayList<>(); people.add(new Person("Alice")); // This will print false because equals is not overridden System.out.println(people.contains(new Person("Alice"))); } }
Output
false
Quick Reference
| Method | Description | Return Type |
|---|---|---|
| contains(Object o) | Checks if the list contains the specified element | boolean |
| add(E e) | Adds an element to the list | boolean |
| remove(Object o) | Removes the first occurrence of the specified element | boolean |
| indexOf(Object o) | Returns the index of the first occurrence of the element | int |
Key Takeaways
Use the contains() method on ArrayList to check if an element exists.
contains() returns true if the element is found, false otherwise.
For custom objects, override equals() and hashCode() for contains() to work correctly.
contains() compares elements using equals(), not reference equality.
Avoid null-related issues by checking for null before calling contains() if needed.