Skip to content

Compare Two HashSet objects in Java Example (equals)

This example shows how to compare two HashSet objects to check if they are equal in Java. This example also shows how to compare HashSet objects using the equals method.

How to compare two HashSet objects for equality in Java?

The HashSet class inherits the equals method from the parent class AbstractSet class.

This method compares the specified object with this Set object and returns true if the specified object is a Set, both have the same number of elements (HashSet size), and every element of this Set is also contained in the specified Set object.

Let’s have a look at the source code of the equals method taken from the OpenJDK 8 AbstractSet class.

As we can see from the code, there are some performance shorts cuts applied before comparing the elements of two Set objects. First of all, it checks if the two references point to the same object, if yes, it returns true. Then, if the specified object is not an instance of a Set, it returns false. Once that check is done, it compares the size of two Set objects. If the size is not the same, the Set objects are not equal.

If sizes are equal for both the Set objects, it checks if all the elements of this Set are also contained in the specified Set object. If yes, it returns true, false otherwise.

In short, the equals method compares two Set objects by elements i.e. the actual content of the Set, not just the references. The below example shows how to use the equals method to compare two HashSet objects.

Output

How to compare two HashSet objects of custom class elements?

Let’s see what happens when we compare the set objects having custom class elements using the equals method.

Output

As we can see from the output, even if the two HashSet objects were having the same custom class objects, the equals method returned false.

As we have seen in the source code of the HashSet equals method given at the top, the equals method checks if all the elements of this Set object are also contained in the specified Set object using the containsAll method. The containsAll method relies on the equals method of the elements to compare the objects.

Since we have not implemented the equals method in our Document custom class, the equals method inherited from the Object class is used which only compares the object references, not the actual content. That is the reason the containsAll returns false and in turn the HashSet equals method returns false.

Let’s implement the equals and hashCode methods in the Document class and try again.

Output

It worked this time. Always remember to override the equals and hashCode methods in your custom class for the HashSet or any other Set comparisons to work properly.

This example is a part of the HashSet in Java Tutorial with Examples.

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

References:
Java 8 HashSet

About the author

Leave a Reply

Your email address will not be published.