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.


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.


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.


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.

Java 8 TreeSet

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