Java传递变量的方式为值传递。
Stackoverflow 上的答案:
目的
实现类似于C的交换函数:
void swap(int *p, int *q)
{
int temp;
temp = *p;
*p = *q;
*q = temp;
}
但是,Java没有指针,无法直接实现交换功能,只能使用一些间接的方法实现交换目的。
方法:
1. 最接近swap
函数的方法
int swap(int a, int b) { // usage: y = swap(x, x=y);
return a;
}
y = swap(x, x=y);
上面的函数泛型化:
<T> T swap(T... args) { // usage: z = swap(a, a=b, b=c, ... y=z);
return args[0];
}
c = swap(a, a=b, b=c)
2. 使用数组等方法
2.1 交换数组中的两个元素
void swap(int i, int j, int[] arr) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
2.2 交换两个等长数组 int[]
的内容
void swap(int[] arr1, int[] arr2) {
int[] t = arr1.clone();
System.arraycopy(arr2, 0, arr1, 0, t.length);
System.arraycopy(t, 0, arr2, 0, t.length);
}
2.3 交换两个BitSet
(使用XOR 交换算法)的内容
void swap(BitSet s1, BitSet s2) {
s1.xor(s2);
s2.xor(s1);
s1.xor(s2);
}
另一个例子, 使用bitwise XOR(^) 操作符:
class Swap
{
public static void main (String[] args)
{
int x = 5, y = 10;
x = x ^ y ^ (y = x);
System.out.println("New values of x and y are "+ x + ", " + y);
}
}
2.4 交换类似Point
类的x
和y
域
void swapXY(Point p) {
int t = p.x;
p.x = p.y;
p.y = t;
}
[1]https://stackoverflow.com/questions/3624525/how-to-write-a-basic-swap-function-in-java
[2]https://stackoverflow.com/questions/2393906/how-do-i-make-my-swap-function-in-java