我想創建一個排序後的Map。我用下面的代碼創建了一個地圖,首先我檢查了這個對象並將這個對象添加到列表中。但是當我嘗試檢查第二個對象時,它會給出ClassCastException。從樹形結構中獲取對象並帶有id拋出異常
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.
}
使用泛型:'地圖<字符串,學生>'。 – 2014-02-10 08:51:51
Post Stacktrace詳細信息 –
@LutzHorn我已經更改爲Map但仍會拋出相同的異常。 –
hellzone