因为String类已经实现了Comparable的接口,如果在程序中要使用自定义的类,那么就要让自定义的类实现Comparable接口,主要是实现CompareTo方法。
下面的程序,如果把Student类实现Comparable接口的内容全部注释的时候就会出现上面的错误。
classStudentimplementsComparable{
private String name;
private Integer score;
public Student (String name, Integer score) {
this.name = name;
this.score = score;
}
publicint compareTo(Object o) {
Studentn = (Student) o;
int a = score.compareTo(n.score);
return (a != 0 ? a : name.compareTo(n.name)); //返回 0 表示 this == obj
//返回正数表示 this > obj返回负数表示 this < obj
}
public String toString() {
return"name:" + name + " score:" +score.toString();
}
}
publicclass ComparableTest {
publicstaticvoid main(String[] args) {
List l1 = newLinkedList();
l1.add(newStudent("ttt", 66));
l1.add(newStudent("bbb", 77));
l1.add(newStudent("ccc", 99));
l1.add(newStudent("fff", 88));
l1.add(newStudent("aaa", 66));
l1.add("1");
System.out.println(l1);
Collections.sort(l1);
System.out.println(l1);
}
}