Fix TreeMap java.lang.ClassCastException – cannot be cast to java.lang.Comparable

This example shows how to fix java.lang.ClassCastException – cannot be cast to java.lang.Comparable exception while adding a key-value mapping to the TreeMap object using the put or other methods.

What is the reason for the java.lang.ClassCastException while adding mappings to the TreeMap in Java?

Let’s first see a small example of the TreeMap having the keys as objects of custom class Employee.

The program will throw “java.lang.ClassCastException: com.javacodeexamples.collections.treemap.Employee cannot be cast to java.lang.Comparable” exception when you run it.

Output

Now if you look at the TreeMap documentation, you will find the following text inside TreeMap constructors section.

Constructs a new, empty tree map, using the natural ordering of its keys. All keys inserted into the map must implement the Comparable interface.

Constructs a new, empty tree map, ordered according to the given comparator. All keys inserted into the map must be mutually comparable by the given comparator.

It means that the objects used as keys of the TreeMap must either implement the Comparable interface, or a custom Comparator must be provided at the TreeMap creation time. In the above example, we did neither of that and that was the reason for the ClassCastException.

How to fix java.lang.ClassCastException while using the TreeMap?

There are a couple of ways to fix this exception, either implement the Comparable interface or provide a custom comparator in the TreeMap constructor.

1. Resolve using the Comparable

The class objects used as keys of the TreeMap can implement the Comparable interface to resolve this exception as given below.

Output

Visit Java Comparable Tutorial for more information on how to implement the Comparable interface.

2. Resolve using the Comparator

You can also provide a custom comparator for the key objects in the TreeMap constructor. In that case, the keys added to the TreeMap object will be ordered using the specified comparator object as given below.

Output

As you can see from the output, the Employee objects are automatically sorted by the specified custom comparator class.

Visit Java Comparator Tutorial for more information on how to implement the Comparator interface.

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

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

References:
Java 8 TreeMap

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