题目
代码
Employee类
package day08.myExer;
/**
* @author Eliot
* @Description
* @date 2022/4/10 11:42
*/
public class Employee implements Comparable<Employee>{
private String name;
private int age;
private MyDate birthday;
public Employee() {
}
public Employee(String name, int age, MyDate birthday) {
this.name = name;
this.age = age;
this.birthday = birthday;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
", birthday=" + birthday +
'}';
}
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;
}
public MyDate getBirthday() {
return birthday;
}
public void setBirthday(MyDate birthday) {
this.birthday = birthday;
}
//重写方法,按照name排序
@Override
public int compareTo(Employee e) {
return this.name.compareTo(e.name);
}
}
MyDate类
package day08.myExer;
/**
* @author Eliot
* @Description
* @date 2022/4/10 11:43
*/
public class MyDate {
private int year;
private int month;
private int day;
public MyDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
@Override
public String toString() {
return "MyDate{" +
"year=" + year +
", month=" + month +
", day=" + day +
'}';
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
}
测试类测试
@Test
public void test04(){
Employee e1 = new Employee("小红",20,new MyDate(2002,6,27));
Employee e2 = new Employee("小绿",21,new MyDate(2001,9,21));
Employee e3 = new Employee("小橙",19,new MyDate(2003,8,12));
Employee e4 = new Employee("小青",20,new MyDate(2002,4,4));
Employee e5 = new Employee("小蓝",20,new MyDate(2002,6,17));
TreeSet<Employee> treeSet = new TreeSet<>(new Comparator<Employee>() {
//重写方法,按照出生日期排序
@Override
public int compare(Employee o1, Employee o2) {
int year = o1.getBirthday().getYear() - o2.getBirthday().getYear();
if (year != 0){
return year;
}
int month = o1.getBirthday().getMonth() - o2.getBirthday().getMonth();
if (month != 0){
return month;
}
return o1.getBirthday().getDay() - o2.getBirthday().getDay();
}
});
treeSet.add(e1);
treeSet.add(e2);
treeSet.add(e3);
treeSet.add(e4);
treeSet.add(e5);
//使用迭代器迭代输出
Iterator<Employee> iterator = treeSet.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
输出结果