黑马程序员技术交流社区
标题:
关于TreeSet的问题
[打印本页]
作者:
大大阳
时间:
2016-3-14 21:44
标题:
关于TreeSet的问题
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方法是怎么执行的?自己也没调用它啊,难道是系统自带调用?
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2