Java ArrayList contains example

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

How to check if ArrayList contains element?

To check if ArrayList contains element, use contains method.

This method returns true if ArrayList contains specified element.

ArrayList contains Example


How to check if ArrayList contains custom class object?

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

ArrayList contains method uses 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 contains method to work.

Consider below given example.


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


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

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


About the author



rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

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