如题,让我们建立一个Employee类来实现Compara接口,并且用Treeset进行有序排列。
直接附上代码,代码中有充分注释:
首先我们看Employee类:
package com.domain;
import java.util.Comparator;
import lombok.*;
/*by csdn
* wxd-屁屁宝宝
* time:2018.9.19
*
* */
@Getter
@Setter
public class Employee implements Comparable<Employee>, Comparator<Employee> {
private String name;
private int age;
private Mydate birthday;
//声明三个变量private类型,因为我用来Jar包中的lombok 所以没有构建getset方法
public Employee(String name, int age, Mydate birthday) {
this.name = name;
this.age = age;
this.birthday = birthday;
}
@Override
public int compareTo(Employee o) {
// TODO Auto-generated method stub
return this.getName().compareTo(o.getName());
//compareTo接口 如java.api中描述的,compareTo是比较当前的值 返回一个1或者0或者-1
}
@Override
public int compare(Employee o1, Employee o2) {
// compare是比较两者的值,若果前者小于后者返回1,相等返回0,大于返回-1;
// TODO Auto-generated method stub
if (o1.getBirthday().getYear() < o2.getBirthday().getYear())
return 1;
else if (o1.getBirthday().getYear() == o2.getBirthday().getYear()) {
if (o1.getBirthday().getYear() < o2.getBirthday().getYear()) {
//此处只是比较了年份 月 日同理 继续在里面添加if循环即可
}
return 0;
}
else
return -1;
}
public Employee() {
super();
}
@Override
public String toString() {
return "Employee [name=" + name + ", age=" + age + ", birthday=" + birthday.toString() + "]\n";
}
}
接下来是MyDate类:
package com.domain;
import lombok.*;
@Getter@Setter
public class Mydate {
private int month;
private int day;
private int year;
public Mydate(int month, int day, int year) {
// TODO Auto-generated constructor stub
this.month = month;
this.day = day;
this.year = year;
}
//
//
// public int compareTo(Mydate m) {
// // TODO Auto-generated method stub
// if (this.getYear() > m.getYear()) {
// return -1;
// } else if (this.getYear() == m.getYear()) {
// if (this.getMonth() > m.getMonth()) {
// return this.getMonth();
// } else if (this.getMonth() == m.getMonth()) {
// if (this.getDay() > m.getDay()) {
// return this.getDay();
// } else if (this.getDay() == m.getDay()) {
// return this.getDay();
// }
//
// }
// return m.getMonth();
// }
// return m.getYear();
// }
@Override
public String toString() {
return "Mydate [month=" + month + ", day=" + day + ", year=" + year + "]";
}
}
//一定要注意,compara是int型,所以你返回的值是int是他不会报错,但是实际中,
//只能是返回三种,1,0,-1
//我就是每注意,然后很尴尬
接下来是测试类:
package com.domain;
import java.util.Set;
import java.util.TreeSet;
public class EmployeeTest {
public static void main(String[] args){
Employee emp1=new Employee("李四", 22, new Mydate(10, 1, 2008));
Employee emp2=new Employee("张三", 21, new Mydate(11, 2, 2018));
Employee emp3=new Employee("王五", 20, new Mydate(12, 3, 1998));
// reportcard.addEmployee(emp1);
// reportcard.addEmployee(emp2);
// reportcard.addEmployee(emp3);
Set<Employee> set=new TreeSet<Employee>(new Employee());
set.add(emp1);
set.add(emp2);
set.add(emp3);
System.out.print(set);
}
}
被我注释的代码都是错误类型,请不要研究,不希望被我误导。
对应的Hashset和Treeset 前者是无序的 后者是有序的。