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);
}
对于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;
}
}
是交换失败的