Compare Two TreeSet in Java Example (equals method)

This example shows how to compare two TreeSet objects in Java. This example also shows how to compare two TreeSet objects using the TreeSet equals method.

How to compare two TreeSet objects in Java using the equals method?

We can check if two TreeSet objects are equal or not using the equals method. The TreeSet class inherits the equals method from the parent class AbstractSet.

The equals method of the TreeSet compares the specified object with this TreeSet object for equality. It returns true if the specified object is a set, both have the same number of elements (having the same size), and every element of the specified set object is also contained in this TreeSet object (using the containsAll method).

In other words, the equals method of the TreeSet class compares two TreeSet objects by elements. If both have the same elements, it returns true, false otherwise.

Output

How to compare TreeSet objects having elements of a custom class?

Let’s first see an example of that.

Output

As we can see from the output, the code threw java.lang.ClassCastException exception. The reason is, all elements of the TreeSet either must implement the Comparable interface and define the compareTo method or a custom Comparator must be provided in the TreeSet constructor.

Let’s implement the Comparable interface in the Document class and try again.

Output

It worked as expected this time.

Tip: Always override the toString, equals, hashCode methods in your custom class.

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

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

References:
Java 8 TreeSet

About the author

RahimV

RahimV

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