想写一个方法来交换main函数中的两个变量值,代码如下:
public class Test {
public static void swap(int x,int y) {
int tmp = x;
x = y;
y = tmp;
}
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println("交换前:"+ a +" " + b);
swap(a,b);
System.out.println("交换后:"+ a +" " + b);
}
}
运行结果:
解析:并未发生交换,这是因为swap()方法中只改变了形参的值,对实参未进行改变,这些交换只发生在栈上
想要改变实参值,可借用数组交换,也可利用类开辟对象空间,通过传址交换,这些交换发生在堆上
代码示例:
class MyValue{
public int val;
}
public class Test {
public static void swap(MyValue myV1,MyValue myV2){
int temp = myV1.val;
myV1.val = myV2.val;
myV2.val = temp;
}
public static void main(String[] args) {
MyValue myValue1 = new MyValue();
MyValue myValue2 = new MyValue();
myValue1.val = 1;
myValue2.val = 2;
System.out.println("交换前:" + myValue1.val + " " + myValue2.val);
swap(myValue1,myValue2);
System.out.println("交换前:" + myValue1.val + " " + myValue2.val);
}
}
解析: