publicclassTestDateSort{/***@paramargs*/publicstaticvoidmain(String[]args){//TODOAuto-generatedmethodstubDatea[]=newDate[5];a[0]=newDate(2011,11,11);a[1]=newDate(2011,11,...
public class TestDateSort {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Date a[] = new Date[5];
a[0] = new Date(2011, 11, 11);
a[1] = new Date(2011, 11, 12);
a[2] = new Date(2010, 11, 11);
a[3] = new Date(2009, 11, 12);
a[4] = new Date(2011, 10, 11);
a = bubbleSort(a);
System.out.println(a[0]);
for (int k = 0; k < a.length; k ++) {
a[k].show();
}
}
public static Date[] bubbleSort(Date[] date) {
int len = date.length;
for (int i = len - 1; i > 0; i --) {
for (int j = 0; j < i; j ++) {
if (date[j].compareDate(date[j + 1]) > 0) {
Date.swap(date[j], date[j + 1]);
}
}
}
return date;
}
}
class Date {
int year, month, day;
public Date(int y, int m, int d) {
this.year = y;
this.month = m;
this.day = d;
}
public int compareDate(Date date) {
return this.year > date.year ? 1
: this.year < date.year ? -1
: this.month > date.month ? 1
: this.month < date.month ? -1
: this.day > date.day ? 1
: this.day < date.day ? -1 : 0;
}
public static void swap(Date x, Date y) {
Date temp = x;
x = y;
y = temp;
}
public void show() {
System.out.println(year + " - " + month + " - " + day);
}
public String toString() {
return ("year - month - day");
}
}
这个是我写的一个关于日期排序的实验
其中swap方法无法实现交换功能
public static void swap(Date x, Date y) {
Date temp = x;
x = y;
y = temp;
}
我很好奇,如何在java中实现类似于c++中的swap功能
swap (obj &x, obj &y)
{
obj temp = x;
x = y;
y = temp
}
小弟在此先感谢各位大虾的指导了!
展开