package myTreeSetDemo;
//排序元素所属类实现Comparable接口,并重写compareTo(T o)方法
public class Student implements Comparable<Student> {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
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 s) {
//相等
// return 0;
//从大到小排序
// return -1;
//从小到大排序
// return 1;
//先比较年龄
int num = this.age - s.age;
//若年龄相等,比较姓名
int num2 = (num == 0 ? this.name.compareTo(s.name) : num);
return num2;
}
}
package myTreeSetDemo;
import java.util.TreeSet;
public class TreeSetComparableDemo {
public static void main(String[] args) {
TreeSet<Student> treeSet = new TreeSet<Student>();
Student s1 = new Student("xiaozhao", 19);
Student s2 = new Student("xiaoli", 20);
Student s3 = new Student("xiaowang", 18);
Student s4 = new Student("xiaoma", 23);
Student s5 = new Student("xiaohua", 20);
Student s6 = new Student("xiaohua", 20);
treeSet.add(s1);
treeSet.add(s2);
treeSet.add(s3);
treeSet.add(s4);
treeSet.add(s5);
treeSet.add(s6);
for (Student s : treeSet) {
System.out.println(s.getName() + "," + s.getAge());
}
}
}
结果: