/*
* 对象数据排序要点:
* 1)用关键字进行比较,决定先后顺序
* 2)元素交换时,用对象引用进行交换
*/
public class sortObjectDemo {
public static void main(String[] args) {
DataOBject objs[] = new DataOBject[6];
objs[0] = new DataOBject("Jack", new MyDatee(1990,1,1), 1.5);
objs[1] = new DataOBject("Tom", new MyDatee(1991,3,1), 20);
objs[2] = new DataOBject("Rose", new MyDatee(1993,5,1), -88.8);
objs[3] = new DataOBject("Mike", new MyDatee(1995,10,1), 10);
objs[4] = new DataOBject("Kobe", new MyDatee(1980,1,6), -5);
objs[5] = new DataOBject("James", new MyDatee(2018,3,18), 0);
bubbleSort(objs);
for(Object obj:objs){
System.out.println(obj);
}
}
public static void bubbleSort(DataOBject objs[]){
for(int i=0;i<objs.length-1;i++){
for(int j=0;j<objs.length-i-1;j++){
if(objs[j].getKey()>objs[j+1].getKey()){//用关键字进行比较,决定先后顺序
swap(objs,j,j+1);
}
}
}
}
//对象交换时,只换引用
private static void swap(DataOBject objs[],int i,int j){
DataOBject tempObj = objs[i];
objs[i]=objs[j];
objs[j]=tempObj;
}
}
public class DataOBject {
private String name;
private MyDatee bithday;
private double key;//代表用于决定排序顺序的字段,你可以理解成年龄、成绩、金额等等
public DataOBject(String name, MyDatee bithday, double key) {
super();
this.name = name;
this.bithday = bithday;
this.key = key;
}
public DataOBject() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public MyDatee getBithday() {
return bithday;
}
public void setBithday(MyDatee bithday) {
this.bithday = bithday;
}
public double getKey() {
return key;
}
public void setKey(double key) {
this.key = key;
}
@Override
public String toString() {
return name + "," + bithday + ","+ key;
}
}
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;
}
}