TreeMap is a class of Java Collection Framework that implements the NavigableMap interface. It stores the map's elements in a tree structure and provides an efficient alternative to storing key-value pairs in sorted order. Please note that while creating a TreeMap object, one must use the Comparable interface or the Comparator interface so that we can maintain the sort order of its elements, otherwise, we will encounter a java.lang.ClassCastException. In this article, we will explain how to use Comparable and Comparator interfaces to resolve ClassCastException issues in TreeMap
Let us start the discussion with a sample program that will show us ClassCastException in TreeMap.
The Chinese translation ofIn the following example, we will try to add a custom class object to the TreeMap without using the Comparable and Comparator interfaces to demonstrate the situation when 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); } }
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)
Let us start the discussion by introducing the Comparable interface
This interface is very useful when we want to sort custom objects in natural order. For example, it sorts strings in lexicographic order and numbers in numerical order. This interface is available in the 'java.lang' package. Generally, the classes and interfaces defined in this package are available to us by default, so there is no need to import this package explicitly.
class nameOfclass implements Comparable<nameOfclass>
Here, class is the keyword to create a class, and implements is the keyword to enable the features provided by the interface.
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.
compareTo(nameOfclass nameOfobject);
The following example demonstrates the use of Comparable in repairing ClassCastException.
Create a class 'TrMap' that implements the Comparable interface. Inside the class, declare two variables and define a constructor with two parameters of type string and double 'item' and 'price'.
Moving further, we will use the 'toString()' method to convert the object's data to a string. Then, define the 'compareTo' method and take an object of class 'TrMap' as a parameter to compare the 'this' object with the newly created object
Now, in the main() method, declare an object of TreeMap class named 'obj' and store the object details into it using the inbuilt method named 'put()'. 'item' is the key and its corresponding value is 'price'.
Finally, use the 'keySet()' method in a for-each loop to retrieve and print the value associated with the key.
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)); } } }
Elements of the map: Item: Kurti, Price: 455 Item: Shirt, Price: 660 Item: TShirt, Price: 495
First, let us introduce the Comparator interface.
As its name suggests, it is used to compare something. In Java, Comparator is an interface for sorting custom objects. We can write our own logic to sort the specified objects in its built-in method named 'compare()'. This method accepts two objects as parameters and returns an integer value. Through this integer value, the Comparator determines which object is larger
class nameOfComparator implements Comparator< TypeOfComparator >() { compare( type object1, type object2 ) { // logic for comparison } }
The following example demonstrates the use of Comparator when repairing ClassCastException.
First, import the 'java.util' package so that we can use TreeSet
Create a class named 'TrMap'. Inside the class, declare two variables and define a constructor that has two parameters 'item' and 'price', which are string type and integer type respectively.
Moving further, we will use the 'toString()' method to convert the object's data to a string
Then, define another class 'Comp' that implements the Comparator interface, in which the 'compare()' method is used to sort the TreeMap in ascending order.
In the 'main()' method, create a TreeMap collection by passing an instance of the 'Comp' class for sorting
Finally, use the 'put()' method to store some elements into the TreeMap collection 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); } }
Elements of the map: {Item: TShirt, Price: 495=1, Item: Shirt, Price: 660=2}
在本文中,我们首先定义了TreeMap类,然后介绍了TreeMap中的ClassCastException。在下一部分中,我们讨论了可以帮助解决这个ClassCastException的Comparator和Comparable接口。然后,我们看到了三个示例程序,展示了ClassCastException以及如何修复这个异常。
The above is the detailed content of How to solve java.lang.ClassCastException issue while using TreeMap in Java?. For more information, please follow other related articles on the PHP Chinese website!