一步一步学习java数组学习(ch5)对象数组的排序

public class Test{
public static void main(String[] args){
Date[] days = new Date[5];
days[0] = new Date(2006,5,4);
days[1] = new Date(2006,7,4);
days[2] = new Date(2008,5,4);
days[3] = new Date(2004,5,9);
days[4] = new Date(2004,5,4);
bubbleSort(days);
for(int i=0;i<days.length;i++){
System.out.println(days[i]); //调用了tostring方法
}
}

public static Date[] bubbleSort(Date[] a){ //冒泡排序
for(int i = a.length-1;i>=1;i--){ //从数组最后一个开始
for(int j = 0;j<=i-1;j++){
if(a[j].compare(a[j+1])>0){ //调用了date类的compare方法
Date tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;
}
}
}
return a;

}
}
class Date{
private int day,month,year;
Date(int year,int month,int day){
this.day = day;
this.month = month;
this.year = year;
}

public int compare(Date d){
return year > d.year? 1
:year < d.year? -1
:month > d.month? 1
:month > d.month? -1
:day > d.day? 1
:day < d.day? -1 : 0;
}
public String toString(){ //重写object类的tostring方法
return "year:month:day"+this.year+"-"+this.month+"-"+this.day;
}
}


 

今天学习的创建对象数组,然后通过对象的比较方法排序。。

执行结果如下

posted @ 2011-11-18 17:29  ①只耳  阅读(260)  评论(0编辑  收藏  举报