对于这个问题,相比于 C语言中较大的区别,首先,如果我们在Java中采用C语言的方式
public class Arithmetic {
public static void main(String[] args) {
int a = 4;
int b = 5;
System.out.println("交换之前a:"+a+" 交换之前b:"+b);
swap(a,b);
System.out.print("交换之后a:"+a+" 交换之后b:"+b);
}
public static void swap(int a,int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
}
交换之前a:4 交换之前b:5
交换之后a:4 交换之后b:5
从结果中很明显可以看出,a,b的值并没发生变化,原因是在Java中并不能通过交换地址的方式来使两个变量值的发生交换。
所以此方法行不通,那么该采用何种方式来实现这个功能呢。这里采用对象的方式可以实现这个功能,代码如下:
public class Arithmetic {
private int x;
private int y;
//public Arithmetic(int x,int y){
this.x = x;
this.y = y;
}
public static void main(String[] args) {
Arithmetic t = new Arithmetic();
t.x = 4;
t.y = 5;
System.out.println("交换之前a:"+t.x+" 交换之前b:"+t.y);
t.swap(t);
System.out.println("交换之后a:"+t.x+" 交换之后b:"+t.y);
}
public static void swap(Arithmetic t)
{
int temp;
temp = t.x;
t.x = t.y;
t.y = temp;
}
}
交换之前a:4 交换之前b:5
交换之后a:5 交换之后b:4
从结果来看已经交换成功了,这是为什么呢?
答案是在此段代码中,将需要交换的值作为成员变量,然后通过创建一个对象,通过对象的引用便能够实现交换啦