Java 如何使用TreeMap时修复java.lang.ClassCastException
TreeMap是Java集合框架中实现NavigableMap接口的类。它将地图的元素存储在树结构中,并提供了一种有效的方式来按排序顺序存储键值对。请注意,在创建TreeMap对象时,必须使用Comparable接口或Comparator接口之一,以便我们可以保持其元素的排序顺序,否则将会遇到java.lang.ClassCastException异常。在本文中,我们将解释如何使用Comparable和Comparator接口来修复TreeMap中的ClassCastException问题。
修复TreeMap中的java.lang.ClassCastException
让我们从一个示例程序开始讨论,该程序将向我们展示TreeMap中的ClassCastException。
示例1
在以下示例中,我们将尝试向TreeMap中添加没有实现Comparable和Comparator接口的自定义类对象,以显示Java编译器抛出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)
如何使用Comparable接口修复java.lang.ClassCastException
让我们通过介绍Comparable接口来开始讨论。
Comparable接口
当我们希望按照自然顺序对自定义对象进行排序时,这个接口很有用。例如,它可以按照字典顺序对字符串进行排序,按照数字顺序对数字进行排序。这个接口在’java.lang’包中可用。一般来说,这个包中定义的类和接口默认可供我们使用,因此不需要显式导入这个包。
语法
class nameOfclass implements Comparable<nameOfclass>
这里,class是创建一个类的关键字,而implements是一个关键字,它使得接口提供的功能可用。
compareTo()
Comparable接口只定义了一个名为’CompareTo’的方法,它可以被重写以对对象的集合进行排序。它赋予了比较一个类的对象与其自身的能力。当’this’对象等于传递的对象时,它返回0;当’this’对象大于传递的对象时,它返回一个正值;否则返回一个负值。
语法
compareTo(nameOfclass nameOfobject);
示例2
下面的示例演示了在修复ClassCastException中使用Comparable的示例。
方法
- 创建一个实现Comparable接口的类“TrMap”。在其中,声明两个变量,并定义一个该类的构造函数,它有两个参数“item”和“price”,分别为字符串和双精度。
-
进一步地,我们将使用“toString()”方法将对象的数据转换为字符串。然后,定义“compareTo”方法,并将一个类“TrMap”的对象作为参数,用于比较“this”对象与新创建的对象。
-
现在,在main()方法中,声明一个名为“obj”的TreeMap类的“TrMap”类型的对象,并使用一个名为“put()”的内置方法将对象的详细信息存储到其中。其中,“item”是键,其对应的值为“price”。
-
最后,使用for-each循环中的“keySet()”方法来检索和打印与键相关联的值。
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
如何使用Comparator解决java.lang.ClassCastException问题
首先,让我们介绍Comparator接口。
Comparator
顾名思义,它用于比较某些东西。在Java中,Comparator是一个用于对自定义对象进行排序的接口。我们可以在其内置的名为’compare()’的方法中编写自己的逻辑,以对指定对象进行排序。该方法接受两个对象作为参数,然后返回一个整数值。根据这个整数值,Comparator决定哪个对象更大。
语法
class nameOfComparator implements Comparator< TypeOfComparator >() {
compare( type object1, type object2 ) {
// logic for comparison
}
}
示例3
下面的示例演示了在修复ClassCastException时使用Comparator。
方法
- 首先,导入’java.util’包,以便我们可以使用TreeSet。
-
创建一个类’TrMap’。在其中声明两个变量,并定义一个构造函数,该类带有两个参数’string’类型的’item’和整数类型的’price’。
-
接下来,我们将使用’toString()’方法将对象的数据转换为字符串。
-
然后,定义另一个类’Comp’,它实现了Comparator接口,在其中使用’compare()’方法以升序排序TreeMap。
-
在’main()’方法内,通过传递’Comp’类的实例来创建一个TreeMap集合,以便对其进行排序。
-
最后,使用’put()’方法将几个元素存储到TreeMap集合中,然后打印结果。
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的情况以及如何修复这个异常。