Java ArrayList contains()

The contains() method checks if the specified element is present in the arraylist.

Example


Syntax of ArrayList contains()

The syntax of the contains() method is:

arraylist.contains(Object obj)

Here, arraylist is an object of the ArrayList class.


contains() Parameter

The contains() method takes a single parameter.

  • obj - element that is checked if present in the arraylist

contains() Return Value

  • returns true if the specified element is present in the arraylist.
  • returns false if the specified element is not present in the arraylist.

Example 1: contains() Method with Integer ArrayList

Output

Number ArrayList: [2, 3, 5]
Is 3 present in the arraylist: true
Is 1 present in the arraylist: false

In the above example, we have created an Integer arraylist named number. Notice the expressions,

// returns true
number.contains(3)

// returns false
number.contains(1)

Here, the contains() method checks if 3 is present in the list. Since 3 is present, the method returns true. However, 1 is not present in the list so the method returns false.


Example 2: contains() Method with String ArrayList

Output

Programming Languages: [Java, JavaScript, Python]
Is Java present in the arraylist: true
Is C++ present in the arraylist: false

In the above example, we have used the contains() method to check if elements Java and C++ are present in the arraylist languages.

Since Java is present in the arraylist, the method returns true. However, C++ is not present in the list. Hence, the method returns false.

Note: The contains() method internally uses the equals() method to find the element. Hence, if the specified element matches with the element in arraylist, the method returns true.