The contains() method of the ArrayList class is used to check whether a specified element exists in the list. It searches the ArrayList for the given element and returns true if the element is found; otherwise, it returns false.
- Uses the equals() method to compare elements.
- Works with primitive wrapper classes, strings, and custom objects.
- Commonly used for searching and validating elements.
import java.util.ArrayList;
public class GFG {
public static void main(String[] args) {
// Create an ArrayList of Strings
ArrayList<String> s = new ArrayList<>();
s.add("Apple");
s.add("Blueberry");
s.add("Strawberry");
// Check if "Grapes" exists in the ArrayList
System.out.println(s.contains("Grapes"));
// Check if "Apple" exists in the ArrayList
System.out.println(s.contains("Apple"));
}
}
Output
false true
Explanation: In this example, an ArrayList of strings is created containing "Apple", "Blueberry", and "Strawberry". The contains() method first checks for "Grapes", which is not present, so it returns false. It then checks for "Apple", which exists in the list, so it returns true.
Syntax
public boolean contains(Object o)
- Parameter: o –> The element whose presence in the ArrayList is to be checked.
- Returns: It returns true if the specified element is found in the list else it returns false.
Example: Using the contains() method to check if the ArrayList of Integers contains a specific number.
import java.util.ArrayList;
public class GFG {
public static void main(String[] args) {
// Create an ArrayList of Integers
ArrayList<Integer> arr = new ArrayList<>();
arr.add(10);
arr.add(20);
arr.add(30);
// Check if 20 exists in the ArrayList
System.out.println(arr.contains(20));
// Check if 40 exists in the ArrayList
System.out.println(arr.contains(40));
}
}
Output
true false
Explanation: An ArrayList<Integer> is created with the values 10, 20, and 30. The contains() method returns true for 20 because it is present in the list and false for 40 because it does not exist.
Example: Using contains() method to verify if the ArrayList of Strings contains a specific name.
import java.util.ArrayList;
public class GFG {
public static void main(String[] args) {
// Create an ArrayList of Strings
ArrayList<String> s = new ArrayList<>();
s.add("Ram");
s.add("Shyam");
s.add("Gita");
// Check if "Hari" exists in the ArrayList
System.out.println(s.contains("Hari"));
// Check if "Ram" exists in the ArrayList
System.out.println(s.contains("Ram"));
}
}
Output
false true
Explanation: An ArrayList<String> containing "Ram", "Shyam", and "Gita" is created. The contains() method returns false for "Hari" since it is not in the list and true for "Ram" because it is present.
Advantages of contains() Method
- Quickly checks whether an element exists in the list.
- Returns a simple boolean result.
- Works with all object types supported by ArrayList.
- Improves code readability by avoiding manual search loops.
- Useful for validation and duplicate checking.