[Java] 交换函数

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类的xy

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值