public class test{
public static void main(String[] args) {
ArrayList<Employee> employees = new ArrayList();
employees.add(new Employee("tom",2200,new Mydate(2002,8,1)));
employees.add(new Employee("milan",2000,new Mydate(2010,5,1)));
employees.add(new Employee("jack",4400,new Mydate(1998,4,1)));
employees.add(new Employee("john",1000,new Mydate(2001,10,1)));
employees.sort(new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
if(!(o1 instanceof Employee && o2 instanceof Employee)){
return 0;
}
// int i = o1.getName().compareTo(o2.getName());
// if(i != 0){
// return i;
// }
int j = o1.getName().length() - o2.getName().length();
if(j != 0){
return j;
}
int i1 = o1.getBirthday().getYear() - o2.getBirthday().getYear();
if(i1 != 0){
return i1;
}
int i2 = o1.getBirthday().getMonth() - o2.getBirthday().getMonth();
if(i2 != 0){
return i2;
}
return o1.getBirthday().getDay() - o2.getBirthday().getDay();
}
});
Iterator<Employee> iterator = employees.iterator();
while (iterator.hasNext()) {
Employee employee = iterator.next();
System.out.println(employee);
}
}
}
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;
}
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;
}
@Override
public String toString() {
return "Mydate{" +
"year=" + year +
", month=" + month +
", day=" + day +
'}';
}
}
class Employee implements Comparable<Employee>{
private String name;
private double sal;
private Mydate birthday;
public Employee(String name, double sal, Mydate birthday) {
this.name = name;
this.sal = sal;
this.birthday = birthday;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
public Mydate getBirthday() {
return birthday;
}
public void setBirthday(Mydate birthday) {
this.birthday = birthday;
}
@Override
public int compareTo(Employee o) {
return Double.compare(this.getSal(),o.getSal());
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", sal=" + sal +
", birthday=" + birthday +
'}';
}
}
泛型+集合+比较的练习
最新推荐文章于 2025-11-23 13:27:25 发布
406






