public class TestDateSort {
public static void main(String[] args) {
Date[] days =
new Date[5
];
days[0] =
new Date(2016, 5, 1
);
days[1] =
new Date(2016, 7, 1
);
days[2] =
new Date(2018, 5, 4
);
days[3] =
new Date(2014, 5, 9
);
days[4] =
new Date(2014, 5, 4
);
System.out.println("排序前: "
);
for(
int i=0; i<days.length; i++
) {
System.out.println(days[i]);
}
bubbleSort(days); //调用冒泡排序
System.out.println("排序后: "
);
for(
int i=0; i<days.length; i++
) {
System.out.println(days[i]);
}
}
//冒泡排序Date[]
private static void bubbleSort(Date[] days) {
int len = days.length-1;
//定义len为数组长度减一
for(
int i = len; i > 0; --
i ) {
for(
int j = 0; j < i; ++
j) {
if(days[j].compare(days[j+1])>0
) {
Date temp =
days[j];
days[j] = days[j+1
];
days[j+1] =
temp;
}
}
}
}
}
//定义一个Date类
class Date{
int year, month, day;
//构造方法
Date(
int year,
int month,
int day){
this.year =
year;
this.month =
month;
this.day =
day;
}
//按年、月、日比较Date的方法
public int compare(Date date) {
return year > date.year ? 1
: year < date.year ? -1
: month > date.month ? 1
: month < date.month ? -1
: day > date.day ? 1
: day < date.day ? -1 : 0
;
}
//重写toString()方法,按照重写的方式输出
@Override
public String toString() {
return "Year:Month:Day -- " + year + "-" + month + "-" +
day;
}
}
输出结果:
排序前: Year:Month:Day -- 2016-5-1Year:Month:Day -- 2016-7-1Year:Month:Day -- 2018-5-4Year:Month:Day -- 2014-5-9Year:Month:Day -- 2014-5-4排序后: Year:Month:Day -- 2014-5-4Year:Month:Day -- 2014-5-9Year:Month:Day -- 2016-5-1Year:Month:Day -- 2016-7-1Year:Month:Day -- 2018-5-4
转载于:https://www.cnblogs.com/pangxiaoshuai/p/10806989.html
相关资源:JAVA上百实例源码以及开源项目