
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Fix ClassCastException While Using TreeMap in Java
TreeMap is a class of Java Collection Framework that implements NavigableMap Interface. It stores the elements of the map in a tree structure and provides an efficient alternative to store the key-value pairs in sorted order. Note that while creating objects of TreeMap it is necessary to use either the Comparable Interface or Comparator Interface so that we can maintain the sorting order of its elements otherwise, we will encounter a java.lang.ClassCastException. In this article, we are going to explain how to use the Comparable and Comparator Interfaces to fix this ClassCastException in TreeMap.
Fixing java.lang.ClassCastException in TreeMap
Let's start this discussion with an example program that will show us the ClassCastException in TreeMap.
Example 1
In the following example, we will try to add custom class objects to TreeMap without Comparable and Comparator Interface to show that the Java compiler throws java.lang.ClassCastException.
import java.util.*; public class TrMap { String item; int price; TrMap(int price, String item) { // this keyword shows these variables belong to constructor this.item = item; this.price = price; } // method for converting object into string public String toString() { return "Item: " + item + ", " + "Price: " + price; } public static void main(String[] args) { // Declaring collection TreeMap TreeMap<TrMap, Integer> obj = new TreeMap<>(); // Adding object to the obj map obj.put(new TrMap(495, "TShirt"), 1); obj.put(new TrMap(660, "Shirt"), 2); // printing details obj map System.out.println("Elements of the map: " + obj); } }
Output
Exception in thread "main" java.lang.ClassCastException: class TrMap cannot be cast to class java.lang.Comparable (TrMap is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap') at java.base/java.util.TreeMap.compare(TreeMap.java:1569) at java.base/java.util.TreeMap.addEntryToEmptyMap(TreeMap.java:776) at java.base/java.util.TreeMap.put(TreeMap.java:785) at java.base/java.util.TreeMap.put(TreeMap.java:534) at TrMap.main(TrMap.java:18)
How to Fix java.lang.ClassCastException using Comparable Interface
Let's begin the discussion by introducing the Comparable Interface.
Comparable Interface
This interface is useful when we want to sort custom objects by their natural ordering. For example, It sorts strings in dictionary order and numerics in numerical order. This interface is available in 'java.lang' package. Generally, classes and interfaces defined in this package are by default available for our use therefore, it is not necessary to import this package explicitly.
Syntax
class nameOfclass implements Comparable<nameOfclass>
Here, class is the keyword that creates a Class and implements is the keyword that enables the use of features provided by an Interface.
compareTo()
The Comparable interface defines only a single method named 'CompareTo' that can be overridden in order to sort the collection of objects. It gives the power to compare the objects of a class to itself. It returns 0 when 'this' object is equal to the passed object, a positive value if 'this' object is greater otherwise a negative value.
Syntax
compareTo(nameOfclass nameOfobject);
Example 2
The following example demonstrates the use of a Comparable in fixing ClassCastException.
Approach
Create a class 'TrMap' that implements a Comparable Interface. Inside it, declare two variables and define a constructor of this class along with two parameters 'item' and 'price' of type string and double respectively.
Moving further we will convert the data of object into a string using 'toString()' method. Then, define 'compareTo' method along with an object of class 'TrMap' as a parameter to compare 'this' object with the newly created object.
Now, in the main() method, declare an object named 'obj' of class 'TrMap' of TreeMap and using an inbuilt method named 'put()' store the details of object to it. The 'item' is key and its corresponding value is 'price'.
In the end, use the 'keySet()' method inside a for-each loop to retrieve and print the values associated with keys.
import java.util.*; import java.lang.*; public class TrMap implements Comparable<TrMap> { String item; int price; TrMap(String item, int price) { // this keyword shows these variables belong to constructor this.item = item; this.price = price; } // method for converting object into string public String toString() { return "Item: " + item + ", " + "Price: " + price; } public String getName() { return this.item; } // overriding method public int compareTo(TrMap comp) { return this.item.compareTo(comp.item); } public static void main(String[] args) { // Declaring collection TreeMap TreeMap<String, TrMap> obj = new TreeMap<>(); // Adding object to the obj map TrMap obj1 = new TrMap("TShirt", 495); obj.put(obj1.getName(), obj1); TrMap obj2 = new TrMap("Shirt", 660); obj.put(obj2.getName(), obj2); TrMap obj3 = new TrMap("Kurti", 455); obj.put(obj3.getName(), obj3); // printing details obj map System.out.println("Elements of the map: "); for (String unKey : obj.keySet()) { System.out.println(obj.get(unKey)); } } }
Output
Elements of the map: Item: Kurti, Price: 455 Item: Shirt, Price: 660 Item: TShirt, Price: 495
How to Fix java.lang.ClassCastException using Comparator
First, let's introduce the Comparator Interface.
Comparator
As the name suggests it is used to compare something. In Java, the Comparator is an interface that is used to sort custom objects. We can write our own logic inside its inbuilt method named 'compare()' to sort the specified objects. This method takes two objects as arguments and then returns an integer value. By this integer value, Comparator decides which object is greater.
Syntax
class nameOfComparator implements Comparator< TypeOfComparator >() { compare( type object1, type object2 ) { // logic for comparison } }
Example 3
The following example illustrates the use of a Comparator in fixing ClassCastException.
Approach
First, import the 'java.util' package so that we can work with TreeSet.
Create a class 'TrMap'. Inside it, declare two variables and define a constructor of this class along with two parameters 'item' and 'price' of type string and integer respectively.
Moving further we will convert the data of object into a string using 'toString()' method.
Then, define another class 'Comp' that implements Comparator Interface and inside it, use the 'compare()' method to sort the TreeMap in ascending order.
Inside the 'main()' method, create a TreeMap collection by passing the instance of 'Comp' class so that it can get sorted.
In the end, store a few elements into the TreeMap collection using 'put()' method and then print the result.
import java.util.*; class TrMap { String item; int price; TrMap(int price, String item) { // this keyword shows these variables belong to constructor this.item = item; this.price = price; } // method for converting object into string public String toString() { return "Item: " + item + ", " + "Price: " + price; } public String getName() { return this.item; } } // use of comparator interface class Comp implements Comparator<TrMap> { // logic to sort public int compare(TrMap i, TrMap j) { if(i.price > j.price) { return 1; } else { return -1; } } } public class Example2 { public static void main(String[] args) { // Declaring collection TreeMap TreeMap<TrMap, Integer> obj = new TreeMap<>(new Comp()); // Adding object to the obj map obj.put(new TrMap(495, "TShirt"), 1); obj.put(new TrMap(660, "Shirt"), 2); // printing details obj map System.out.println("Elements of the map: " + obj); } }
Output
Elements of the map: {Item: TShirt, Price: 495=1, Item: Shirt, Price: 660=2}
Conclusion
In this article, we first defined the TreeMap class and then, introduced the ClassCastException in TreeMap. In the next section, we discussed the Comparator and Comparable Interfaces that can be helpful in fixing this ClassCastException. Then, we have seen three example programs that show ClassCastException and how to fix this exception.