在执行下面提到的代码时,我得到
Exception in thread "main" java.lang.ClassCastException: com.test.tree.T1 cannot be cast to com.test.tree.T2
at com.test.tree.TestComparator.compare(TestTreeMap.java:59)
at java.util.TreeMap.put(TreeMap.java:530)
at com.test.tree.TestTreeMap.main(TestTreeMap.java:22)
代码:
package com.test.tree;
import java.util.Comparator;
import java.util.TreeMap;
public class TestTreeMap{
public static void main(String[] args) {
TreeMap tree=new TreeMap(new TestComparator());
T1 t1=new T1(10, 20);
T2 t2=new T2(10,21);
tree.put(t1, 23);
tree.put(t2, 24);
}
}
class T1 {
int x,y;
public T1(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
class T2 {
int x,y;
public T2(int x,int y) {
super();
this.x = x;
this.y = y;
}
}
class TestComparator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
System.out.println("hi im called");
T1 t1=(T1)o1;
T2 t2=(T2)o2;
return t1.x-t2.y;
}
}
最佳答案
您不能假设 compare
将始终接收 T1
实例作为第一个参数,并接收 T2
实例作为第二个参数。它可能会接收两个 T1
实例或两个 T2
实例,或两者的实例,但不是按照您期望的顺序。
在将 o1
和 o2
转换为 T1
或 T2
之前,您必须测试它们的类型。
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof T1) {
if (o2 instanceof T2) {
T1 t1=(T1)o1;
T2 t2=(T2)o2;
return t1.x-t2.y;
} else {
...
}
} else {
...
}
}
这是假设您的 TreeMap
的键只能是 T1
或 T2
。
关于java - 我们如何在 TreeMap 中使用异构键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34591349/