使用TreeSet或TreeMap时出现的异常:cannot be cast to java.lang.Comparable;
在使用TreeSet或者TreeMap来保存自定义对象时,必须让自定义对象的类实现Comparable接口,并重写其compareTo()方法,否则会报cannot be cast to java.lang.Comparable异常。
实体类Student
public class Student implements Comparable<Student> {
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Student o) {
int num = this.age - o.age; //以年级为主要条件比较
return num == 0 ? this.name.compareTo(o.name) : num;
}
}
测试如下:
@Test
public void test() {
Student stu = new Student("张三",13);
Student stu1 = new Student("李四",12);
//TreeSet测试
TreeSet<Student> set = new TreeSet<Student>();
set.add(stu);
set.add(stu1);
for(Student s : set) {
System.out.println(s.getName()+"="+s.getAge());
}
//TreeMap测试
TreeMap<Student,String> tm = new TreeMap<Student,String>();
tm.put(stu, "哈哈");
tm.put(stu1, "嘿嘿");
for(Student s : tm.keySet()) {
System.out.println(s.getName()+"="+s.getAge());
}
}