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


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.


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.


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



My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *

Online Shopping