java 函数中交换对象_Java中实现类交换的方法

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

}

小弟在此先感谢各位大虾的指导了!

展开

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值