Last Updated : 10 Dec, 2024
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"));
}
}
Syntax of ArrayList.contains() Method
public boolean contains(Object o)
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));
}
}
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"));
}
}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4