Java中的Swap,如何实现?

程序员都知道,在C/C++里面交换值的方法:

void swap(int &a,int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}

但是在Java中这种方法是行不通的,因为Java对普通类型的变量是不支持引用传递的。  

怎么办呢?


 

1.可以像下面这样通过传数组(也属于传值)的方法来完成交换(很多排序算法就是这样实现)。

public static void swap(int[] data,int a,int b){
int temp=data[a];
data[a]=data[b];
data[b]=temp;
}
package pkg2020华南虎;

/**
 *
 * @author yl
 */
public class SwapValue {

    public static void main(String[] args) {
        SwapValue sv = new SwapValue();
        int[] num = new int[2];
        num[0] = 20;
        num[1] = 30;
        sv.swap(num, 0, 1);
        System.out.println("num1,num2:" + num[0] + "," + num[1]);
    }

    public static void swap(int[] data, int a, int b) {

        int temp = data[a];
        data[a] = data[b];
        data[b] = temp;
    }
}

或者

package pkg2020华南虎;

/**
 *
 * @author yl
 */
public class SwapValue {

    public static void main(String[] args) {

        int[] num = new int[2];
        num[0] = 20;
        num[1] = 30;
        swap(num, 0, 1);
        System.out.println("num1,num2:" + num[0] + "," + num[1]);
    }

    public static void swap(int[] data, int a, int b) {

        int temp = data[a];
        data[a] = data[b];
        data[b] = temp;
    }
}

注意:数组排序从0开始。  


2.也可以通过重新定义个类(在Java中我们可以通过使用int的包装类——integer,然后将其作为值得引用传到函数中,但这个integer包装类也不允许你来改变它的数据域;但这不妨碍我们用自己的包装类,比如说下面实现的MyInteger():

package pkg2020华南虎;

/**
 *
 * @author yl
 */
//MyInteger:于Integer类似,但是其对象可以变值
class MyInteger {

    private int x;//将x作为唯一的数据成员

    public MyInteger(int xIn) {
        x = xIn;
    }//构造器

    public int getValue() {
        return x;
    }//得到值

    public void insertValue(int xIn) {
        x = xIn;
    }//改变值
}

public class SwapValue02 {

    static void swap(MyInteger xWrap, MyInteger yWrap) {
        int temp = xWrap.getValue();
        xWrap.insertValue(yWrap.getValue());
        yWrap.insertValue(temp);
    }

    public static void main(String[] args) {
        int a = 23, b = 25;
        MyInteger aWrap = new MyInteger(a);
        MyInteger bWrap = new MyInteger(b);
        swap(aWrap, bWrap);
        a = aWrap.getValue();
        b = bWrap.getValue();
        System.out.println("a,b is: " + a + "," + b);
    }
}

3.由于Java中的参数传递都是采用的值传递方式,这不妨碍我们用swap的时候采用外部内联的方式:  

package pkg2020华南虎;

/**
 *
 * @author yl
 */
public class SwapValue03 {

    int i, j;

    public static void main(String[] args) {
        SwapValue03 sv = new SwapValue03(1, 2);
        sv.swap();
        System.out.println("i,j =" + sv.i + "," + sv.j);
    }

    public SwapValue03(int i, int j) {//构造方法
        this.i = i;
        this.j = j;
    }

    public void swap() {
        int temp = i;
        i = j;
        j = temp;
    }
}

 

posted @ 2020-02-01 17:17  yl新蜜蜂  阅读(1911)  评论(0编辑  收藏  举报