上執行下面提到的代碼,我得到我們如何使用不同種類的鑰匙在TreeMap中
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;
}
}
感謝@Eran,我是有點困惑 – JavaStack
但如果有多種類型的候選關鍵.......那麼任何通用的方法來做到這一點? – JavaStack