English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java ArrayList contains() method is used to check if the specified element exists in the arraylist.
The syntax of the contains() method is:
arraylist.contains(Object obj)
obj - Used to check whether the element exists in the arraylist
If the specified element exists in the arraylist, it returns true.
If the specified element does not exist in the arraylist, it returns false.
import java.util.ArrayList; class Main { public static void main(String[] args) { //Create ArrayList ArrayList<Integer> numbers = new ArrayList<>(); //Insert the element into the arraylist numbers.add(2); numbers.add(3); numbers.add(5); System.out.println("Number ArrayList: "); + numbers); //Check if the element exists in the arraylist 3 System.out.print("Whether the element exists in arraylist: ");3whether: "); System.out.println(numbers.contains(3)); //Check if the element exists in the arraylist1 System.out.print("Whether the element exists in arraylist: ");1whether: "); System.out.println(numbers.contains(1)); {} {}
Output Result
Number ArrayList: [2, 3, 5] There is arraylist with3whether: true There is arraylist with1whether: false
In the above example, we created an integer type ArrayList named number. Note these expressions,
// Returns true number.contains(3) // Returns false number.contains(1)
Here, the contains() method checks for the existence of the element in the list3This method returns true. However, the element does not exist in the list1Therefore, this method returns false.
import java.util.ArrayList; class Main { public static void main(String[] args) { // Create ArrayList ArrayList<String> languages = new ArrayList<>(); //Insert the element into the arraylist languages.add("Java"); languages.add("JavaScript"); languages.add("Python"); System.out.println("Programming language: "); + languages); //Check if Java exists in languages System.out.print("Java whether exists in arraylist: "); System.out.println(languages.contains("Java")); //Find C ++Whether it exists in languages System.out.print("Whether C exists in the array list ++: "); System.out.println(languages.contains("C++")); {} {}
Output Result
Programming Languages: [Java, JavaScript, Python] Does Java exist in the arraylist: true Whether C exists in the array list ++: false
In the above example, we used the contains() method to check if the elements Java and C++, whether they exist in languages.
Since Java exists in the arraylist, this method returns true. But, C++It is not in the list. Therefore, the method returns false.
NoteThe :contains method uses the equals() method internally to find elements. Therefore, if the specified element matches the element in the arraylist, the method returns true.