您的位置:首页 > 编程语言 > Java开发

java例程练习(对象类型数据的排序)

2012-04-29 15:23 525 查看
public class TestSort {
public static void main(String[] args) {
Date[] days =  new Date[5];
days[0] = new Date(2004, 8, 6);
days[1] = new Date(2007, 4, 6);
days[2] = new Date(2007, 4, 9);
days[3] = new Date(2004, 4, 6);
days[4] = new Date(2004, 4, 5);

bubbleSort(days);

for(int i = 0; i < days.length; i++) {
System.out.println(days[i]);
}
}

public static Date[] bubbleSort(Date[] a) {
int len = a.length;
for(int i = len - 1; i >= 1; i--) {
for(int j = 0; j <= i -1; j++) {
if(a[j].compare(a[j + 1]) > 0) {
Date temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
return a;
}
}

class Date {
int year;
int month;
int day;

Date(int y, int m, int d) {
year = y;
month = m;
day = d;
}

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;
}

public String toString() {
return "" + year + "-" + month + "-" + day;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: