import java.util.Arrays;
/*
演示用Arrays.sort()来排序
*/
public class sortObjectDemo2 {
public static void main(String[] args) {
DataOBject2 objs[] = new DataOBject2[6];
objs[0] = new DataOBject2("Jack", new MyDatee(1990,1,1), 1.5);
objs[1] = new DataOBject2("Tom", new MyDatee(1991,3,1), 20);
objs[2] = new DataOBject2("Rose", new MyDatee(1993,5,1), -88.8);
objs[3] = new DataOBject2("Mike", new MyDatee(1995,10,1), 10);
objs[4] = new DataOBject2("Kobe", new MyDatee(1980,1,6), -5);
objs[5] = new DataOBject2("James", new MyDatee(2018,3,18), 0);
Arrays.sort(objs);
for(Object obj:objs){
System.out.println(obj);
}
}
}
public class DataOBject2 implements Comparable<DataOBject2>{
private String name;
private MyDatee birthday;
private double key;代表用于决定排序顺序的字段,你可以理解成年龄、成绩、金额等等
public DataOBject2(String name, MyDatee birthday, double key) {
this.name = name;
this.birthday = birthday;
this.key = key;
}
public DataOBject2() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public MyDatee getBirthday() {
return birthday;
}
public void setBirthday(MyDatee birthday) {
this.birthday = birthday;
}
public double getKey() {
return key;
}
public void setKey(double key) {
this.key = key;
}
@Override
public String toString() {
return name + "," + birthday+ ", " + key ;
}
@Override
public int compareTo(DataOBject2 o) {
/*if(this.key>o.key){
return -1;
}else if(this.key<o.key){
return 1;
}else{
return 0;
}*/
return -(this.getBirthday().getYear()-o.birthday.getYear());
}
}
public class MyDatee {
private int year;
private int month;
private int day;
public MyDatee(int year, int month, int day) {
super();
this.year = year;
this.month = month;
this.day = day;
}
public MyDatee() {
super();
}
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 "["+ year + "年" + month + "月" + day
+ "日]";
}
}