我想创建一个排序的 map 。我使用下面的代码创建了一个 map ,首先我检查了该对象并将该对象添加到列表中。但是当我尝试检查第二个对象时,它给出了 ClassCastException。
java.lang.ClassCastException: java.lang.String cannot be cast to myapplication.Student
这是我的代码;
Map students = new TreeMap(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
if(s1.getName() == null || s2.getName() == null){
return -1;
}
return s1.getName().compareTo(s2.getName());
}
});
Student student = (Student) students.get("23123");
if (student == null) {
student= new Student("321312", "sfsfsfs");
students.put("23123", student);
}
Student student2 = (Student) students.get("42131");//this line throws exception
if (student2 == null) {
student2 = new Student("421321", "dgdfs");
students.put("42131", student2);
}
我的Student.java类;
public class Student {
private String name;
private String number;
//const, getters and setters.
}
最佳答案
在TreeMap
中,Comparator
是比较键而不是值。第一个 get
和 put
成功,因为 map 是空的,不需要调用比较器。但是第二个get
需要比较器将 key 与现有 key 进行比较。您的输入键是 String
类型,而比较器将其处理为 Student
类型。然后抛出一个ClassCastException
。
将您的 map 声明为:
Map<String, Student> students = new TreeMap<String, Student>();
然后就可以了。请注意,您不需要为 String
键类型提供 Comparetor
,因为 String
已经是Comparable
。
关于java - 从 Treemap 获取带有 id 的对象会引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21672553/