Skip to content

Java ArrayList contains example

Java ArrayList contains example shows how to check if ArrayList contains an element in Java. The example also shows how to check if ArrayList contains string or ArrayList contains a custom object.

How to check if ArrayList contains an element?

To check if ArrayList contains an element, use the contains method.

This method returns true if ArrayList contains specified element, false otherwise.

ArrayList contains example

Output

How to check if ArrayList contains a custom class object?

When comparing objects, the contains method returns true if and only if the ArrayList contains an element e such that (o == null ? e == null : o.equals(e)).

The ArrayList contains method uses the equals method to check if it contains the specified object. If ArrayList contains custom class objects, the class must implement the equals method in order for the contains method to work.

Consider below given example.

Output

As you can see from the output, even if the ArrayList contains “Java”, the contains method returned false. That is because the Language class does not implement the equals method which is used by the contains method to compare the objects. Let’s implement the equals method in the Language class and re-run the code.

Output

Note: it is always recommended to implement the hashCode method along with the equals method.

This example is a part of the Java ArrayList tutorial with examples.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.