使用自定义类作为键时使用Java的TreeMap强制转换ClassCastException
当我试图以自定义Dog
类作为键获取映射时,以下代码抛出一个ClassCastException
:
import java.util.TreeMap;
public class testMain {
public static void main(String[] args) {
TreeMap<Dog, String> m = new TreeMap<Dog, String>();
m.put(new Dog("Fido"), "woof");
// this line produces a ClassCastException
String sound = m.get(new Dog("Fido"));
System.out.println(sound);
}
}
狗的种类很简单:
public class Dog {
String name;
public Dog(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
我不明白为什么TreeMap
首先会选Dog
类当使用定制类作为密钥时,为什么会出现ClassCastException任何关于如何修复此代码的想法都将不胜感激
# 1 楼答案
TreeMap根据元素键的顺序在插入时对元素进行排序。因此,用作键的对象必须实现
Comparable
接口请参考我对
Dog
类所做的编辑。它现在起作用了:编辑:ClassCastException异常的原因:
如果在
TreeMap
的get
方法的代码中看到Comparable<? super K> k = (Comparable<? super K>) key;
行,您将看到它正试图将密钥强制转换到Comparable
对象。您的对象不是Comparable
的实例# 2 楼答案
如果你想在没有比较器的树形图中将其用作键,Dog必须实现Comparable
# 3 楼答案
你必须让你的狗类实现
Comparable
接口从文件中: