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); } }
对于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; } } 是交换失败的
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); }}
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);
}
}
对于类类型,传递的是引用的副本
所以总体来说不能通过函数交换值,但可以通过函数修改值
例如
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;
}
}
是交换失败的
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);
}}
b--->对象2<----b'
进入函数体后副本发生了交换,如下图示:
a-->对象1<---b'
b-->对象2<---a'