Skip to content

Java TreeSet Fix java.lang.ClassCastException: cannot be cast to java.lang.Comparable

This example shows how to solve TreeSet java.lang.ClassCastException: cannot be cast to java.lang.Comparable exception while working with the custom class objects.

What is the reason for TreeSet java.lang.ClassCastException exception?

Let’s first see a small example of TreeSet of a custom class objects as elements.

Output

In order to understand the reason for this exception, we need to look at the TreeSet documentation. Here is what it says.

A NavigableSet implementation based on a TreeMap. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

So it says that the TreeSet elements are ordered using the natural ordering or a Comparator provided in the TreeSet constructor. We used a default constructor and did not provide the comparator object when we created the TreeSet object.

The natural order of the element is defined by the Comparable interface and we did not implement that either in the Emp custom class. That is the reason we got the “java.lang.ClassCastException: com.javacodeexamples.collections.treeset.Emp cannot be cast to java.lang.Comparable” exception.

How to fix java.lang.ClassCastException while working with the TreeSet?

We need to either implement the Comparable interface and define the compareTo method in Emp custom class or provide a custom Comparator object while creating the TreeSet to solve this exception. I am going to show you both.

1. By implementing the Comparable interface

Let’s implement the Comparable interface and define the compareTo method in the Emp class.

Output

Once we implement the Comparable interface and define the compareTo method, we will no longer get the java.lang.ClassCastException exception.

2. By providing a custom Comparator in TreeSet constructor

Another alternative is to create a custom Comparator class and provide its object in the TreeSet constructor as given below.

Output

As we can see from the output, we have no longer received the ClassCastException and all Emp objects were sorted in the ascending order by the custom comparator.

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

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

References:
Java 8 TreeSet

About the author

Leave a Reply

Your email address will not be published.