Java ArrayList contains() Method
The contains() method is used to determine whether an element is present in the dynamic array.
The syntax for the contains() method is:
arraylist.contains(Object obj)
Note: arraylist is an object of the ArrayList class.
Parameter Description:
- obj - The element to be checked
Return Value
Returns true if the specified element exists in the dynamic array.
Returns false if the specified element does not exist in the dynamic array.
Example
Using the contains() method with a dynamic array of String type:
Example
import java.util.ArrayList;
class Main {
public static void main(String[] args){
// Create an array
ArrayList<String> sites = new ArrayList<>();
sites.add("Google");
sites.add("tutorialpro");
sites.add("Taobao");
System.out.println("Website List: " + sites);
// Check if tutorialpro is in this array
System.out.print("Is tutorialpro in the arraylist: ");
System.out.println(sites.contains("tutorialpro"));
// Check if Weibo is in this array
System.out.print("Is Weibo in the arraylist: ");
System.out.println(sites.contains("Weibo"));
}
}
Executing the above program outputs:
Is tutorialpro in the arraylist: true
Is Weibo in the arraylist: false
In the above example, we create a dynamic array named sites. Note the expressions:
sites.contains("tutorialpro")
sites.contains("Weibo")
In the above code, the contains() method checks if tutorialpro is in the dynamic array. Since tutorialpro is present, the method returns true. However, Weibo is not in the list, so the method returns false.
Note: The contains() method internally uses the equals() method to find the element. If the specified element matches any element in the array, the method returns true.
Using the contains() method with a dynamic array of Integer type:
Example
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// Create an array
ArrayList<Integer> numbers = new ArrayList<>();
// Insert elements into the array
numbers.add(2);
numbers.add(3);
numbers.add(5);
System.out.println("Number ArrayList: " + numbers);
// Check if 3 is in this array
System.out.print("Is 3 in the arraylist: ");
System.out.println(numbers.contains(3));
// Check if 1 is in this array
System.out.print("Is 1 in the arraylist: ");
System.out.println(numbers.contains(1));
}
}
Executing the above program outputs:
Number ArrayList: [2, 3, 5]
Is 3 in the arraylist: true
Is 1 in the arraylist: false
In the above code, the contains() method checks if 3 is in the dynamic array. Since 3 is present, the method returns true. However, 1 is not in the list, so the method returns false. Java ArrayList