实现Comparable接口后边为什么要加泛型<Student>
class Student implements Comparable<Student> {
private String name;
private int age;
private int score;
Student(String name, int age, int score) {
this.name = name;
this.age = age;
this.score = score;
}
// 重写hashCode()和equals()方法为了保证对象的唯一性
public int hashCode() {
return name.hashCode() + age * 34;
}
public boolean equals(Object obj) {
if (!(obj instanceof Student))
throw new RuntimeException("类型不匹配");
Student s = (Student) obj;
return this.name.equals(s.name) && this.age == s.age
&& this.score == s.score;
}
// 重写compareTo方法(存入二叉树结构集合必备)
public int compareTo(Student s) {
int num = new Integer(this.score).compareTo(new Integer(s.score));
if (num == 0)
return this.name.compareTo(s.name);
return num;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
public String toString() {
return "姓名:" + name + ",年龄:" + age + ",分数:" + score;
}
} |
|