Open In App

Arraylist.contains() Method in Java

Last Updated : 10 Dec, 2024
Suggest changes
Share
Like Article
Like
Report

In Java, the ArrayList contains() method is used to check if the specified element exists in an ArrayList or not. 

Example: Here, we will use the contains() method to check if the ArrayList of Strings contains a specific element.

Java
// Java program to demonstrate the use of contains()  // method with ArrayList of Strings 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 

Syntax of ArrayList.contains() Method

public boolean contains(Object o)

  • Parameter: o: The element whose presence in the ArrayList is to be tested.
  • Returns: It returns true if the specified element is found in the list else it returns false.

Other Examples of Java ArrayList.contains()

Example 2: Here, we are using the contains() method to check if the ArrayList of Integers contains a specific number.

Java
// Java program to demonstrate the use of contains()  // method with ArrayList of Integers 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 


Example 3: Here, we are using contains() method to verify if the ArrayList of Strings contains a specific name.

Java
// Java program to demonstrate the use of contains()  // method with ArrayList of Strings (Names) 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 

Next Article

Similar Reads