package com.heima.bean;
public class Person implements Comparable<Person> {
private String name;
private int age;
...
...
@Override
//按照年龄排序
public int compareTo(Person o) {
int num = this.age - o.age; //年龄是比较的主要条件
return num == 0 ? this.name.compareTo(o.name) : num; //姓名是比较的次要条件
}
}
package com.heima.set;
import java.util.TreeSet;
import com.heima.bean.Person;
public class Demo06_TreeSet {
public static void main(String[] args) {
TreeSet<Person> ts = new TreeSet<>();
ts.add(new Person("张三", 23));
ts.add(new Person("李四", 13));
ts.add(new Person("周七", 13));
ts.add(new Person("王五", 43));
ts.add(new Person("赵六", 33));
System.out.println(ts);
}
}