java 的swap函数怎么写的

renzaijiang 2006-12-19 04:25:03
偶知道 c++是用引用和指针来传递 直接传地址
java里面是怎么个写法
传递过程是咋样的
...全文
921 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
superhemiao 2007-04-03
  • 打赏
  • 举报
回复
根本 原因是所有的传递 都是 pass by value。修改的是引用的副本,而没有修改引用本身,传递数组是通常的 方法,修改的是对象本身。
renzaijiang 2007-02-11
  • 打赏
  • 举报
回复
a--->对象1<----a'(其中a',b'分别为a,b在传递参数的时候产生的副本)
b--->对象2<----b'
进入函数体后副本发生了交换,如下图示:
a-->对象1<---b'
b-->对象2<---a'
renzaijiang 2007-02-11
  • 打赏
  • 举报
回复
public class Swap {
private int x, y;

public Swap(int x, int y) {
this.x = x;
this.y = y;
}

public void doSwap() {
int i = this.y;
this.y = this.x;
this.x = i;
}

public int getX() { return x;}
public int getY() { return y;}

public static void main(String[] args) {
int x = 5;
int y = 6;
System.out.println("x=" + x);
System.out.println("y=" + y);
System.out.println("----------------");
Swap s = new Swap(x, y);
s.doSwap();
x = s.getX();
y = s.getY();
System.out.println("x=" + x);
System.out.println("y=" + y);
}

}
88324877 2006-12-19
  • 打赏
  • 举报
回复
用数组 或自己编的类传递参数
XXKKFF 2006-12-19
  • 打赏
  • 举报
回复
对于int,float这样的原生类型是和c++一样的
对于类类型,传递的是引用的副本
所以总体来说不能通过函数交换值,但可以通过函数修改值
例如
class Swap{
public static void main( String[] args ){
Integer a = new Integer(10);
Integer b = new Integer(20);
Swap.swap(a,b);
System.out.println( a );
System.out.println( b );
}
static void swap(Integer a,Integer b){
Integer temp;
temp = a;
a = b;
b = temp;
}
}
是交换失败的
dreamover 2006-12-19
  • 打赏
  • 举报
回复
public class Test{
class Temp{
int x;
int y;
}

void swap(Temp temp){
int t = temp.x;
temp.x = temp.y;
temp.y = t;
}

public static void main(String[] args){
Temp tem = new Temp();
tem.x = 1;
tem.y = 2;
swap(tem);
System.out.println(tem.x);
System.out.println(tem.y);
}
}
fool_leave 2006-12-19
  • 打赏
  • 举报
回复
no way

只可以改变传入参数Object的属性值,而不能改变两个Object的指向

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧