class Student implements Comparable<Student>{
String name;
int age;
char sex;
public Student(String name,int age, char sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public int compareTo(Student o){
if (o == null) {
return 0;
}
int n1 = this.name.compareTo(o.name);
int n2 = (n1 == 0 ? this.age - o.age : n1);
int n3 = (n2 == 0 ? this.sex - o.sex : n2);
return n3;
}
}
public class Exercise{
public static void main(String[] args) {
Set<Student> stuTree = new TreeSet<>();
stuTree.add(new Student("宋小宝",22,'男'));
stuTree.add(new Student("刘能",33,'男'));
stuTree.add(new Student("赵四",44,'男'));
stuTree.add(new Student("小沈阳",55,'男'));
stuTree.add(new Student("小沈阳",43,'男'));
stuTree.add(new Student("小沈阳",55,'男'));
stuTree.add(new Student("小沈阳",55,'女'));
Iterator it = stuTree.iterator();
while(it.hasNext()){
Student stu =(Student)it.next();
System.out.println(stu.name + "," +stu.age + "," + stu.sex);
}
}
重写的compareTo方法是怎么执行的?自己也没调用它啊,难道是系统自带调用?
|
|