简述
java中传递数据都是先拷贝的。所以,在函数调用的时候,是不存在类似于C++的操作的。
对于想要简洁的交换的朋友们,可以死心了
但是总是可以想到些看起来简洁的方法
方法
方法一: 函数返回的时候构造出数组来,这样就再来获取
要注意的是,因为main函数是static的函数,所以,如果想要调用类内函数的话,类内函数也必须是static标记的
public class Test {
public static void main(String[] args) {
int a = 1, b = 2;
int[] temp = swap(a, b);
a = temp[0]; b = temp[1];
System.out.println(a);
System.out.println(b);
}
static int[] swap(int a, int b) {
return new int[] {b, a};
}
}
讲道理,其实这个代码还是比较冗余。
其实这样的话,还不如改写一下
public class Test {
public static void main(String[] args) {
int a = 1, b = 2;
int[] temp = {b, a};
a = temp[0];
b = temp[1];
System.out.println(a);
System.out.println(b);
}
}