java中实现swap解决方案
由于java中“对基本类型的变量是不支持引用传递的”,所以根本不能像c/c++那样直接传地址,但是可以如下解决:
1.使用数组传值
public class TestSwap2 {
//由于java中的参数传递都是采用值传递的传递方式,因此不能使用引用符号。
//可以使用重新赋值的方法
private static int[] swap(int a, int b){
int temp = a;
a = b;
b = temp;
return new int[]{a,b};
}
//下面是主函数的实现
public static void main(String[] args){
int a = 4;
int b = 6;
System.out.println("before swap "+"a的值="+a+" b的值="+b);
int[] swap = swap(a,b);
a = swap[0];
b = swap[1];
System.out.print(a + " ");
System.out.print(b);
System.out.println("======");
System.out.println("after swap "+"a的值="+a+" b的值="+b);
}
}
2.采用类变量传值
public class TestSwap { /** * @param args */
//定义类变量
static int a = 3;
static int b = 2;
public static void main(String[] args) {
TestSwap ts = new TestSwap();
System.out.println("before swap "+"a的值="+ts.a+" b的值="+ts.b);
ts.swap(ts);
System.out.println("after swap "+"a的值="+ts.a+" b的值="+ts.b);
}
//改变的是类变量的值
private static void swap(TestSwap ts)
{
int temp;
temp = ts.a;
ts.a = ts.b;
ts.b = temp;
}
}
3.采用外部内联
public class TestSwap1 {
//外部内联的方式
static int a = 3;
static int b = 2;
public static void main(String[] args){
Exchange exc = new Exchange(a,b);
System.out.println("before swap "+"a的值="+a+" b的值="+b);
exc.swap(exc);
//System.out.print(exc.i);
a=exc.i;
b=exc.j;
System.out.println("after swap "+"a的值="+a+" b的值="+b);
}
}
class Exchange{
int i , j;
Exchange(int i, int j){
this.i = i;
this.j = j;
}
public void swap(Exchange exc)
{
int temp = exc.i;
exc.i = exc.j;
exc.j = temp;
}
}
4.采用包装类传
//MyInteger: 与Integer有些类似,但是其对象可以变值
class MyInteger {
private int x; // 将x作为唯一的数据成员
public MyInteger(int xIn) { x = xIn; } // 构造器
public int getValue() { return x; } // 得到值
public void setValue(int xIn) { x = xIn;} // 改变值
}
public class TestSwap3 {
// swap: 传对象引用
static void swap(MyInteger rWrap, MyInteger sWrap) {
// 变值过程
int t = rWrap.getValue();
rWrap.setValue(sWrap.getValue());
sWrap.setValue(t);
}
public static void main(String[] args) {
int a = 23, b = 47;
System.out.println("before swap "+"a的值="+a+" b的值="+b);
MyInteger aWrap = new MyInteger(a);
MyInteger bWrap = new MyInteger(b);
swap(aWrap, bWrap);
a = aWrap.getValue();
b = bWrap.getValue();
System.out.println("After swap "+"a的值="+a+" b的值="+b);
}
}
参考博客
[1] http://blog.csdn.net/dadoneo/article/details/6577976?reload