网红问题(值传递)

public class ValueTransferTest1 {
    public static void main(String[] args) {

        int m = 10;
        int n = 20;

        System.out.println("m = " + m + ", n = " + n);

        ValueTransferTest1 test = new ValueTransferTest1();
        test.swap(m, n); //使用完销毁(弹出栈)
        System.out.println("m = " + m + ", n = " + n); //此时的m,n仍然是main里面的m,n

        test.swap1(m, n);

        test.swap2(m, n);

        test.swap3(m, n);

    }
    //错误写法
    public void swap(int m, int n){
        int temp = m;
        m = n;
        n = temp;
    }
    //正确写法一(繁琐)
    public void swap1(int m, int n){
        int temp = m;
        m = n;
        n = temp;
        int[] arr = new int[2];
        arr[0] = m;
        arr[1] = n;
        System.out.println("swap1:" + "m = " + arr[0] + ", n = " + arr[1]);
//        System.out.println(Arrays.toString(arr));
    }
    //正确写法二(稍改)
    public void swap2(int m, int n){
//        int temp = m;
//        m = n;
//        n = temp;
        int[] arr = new int[2];
        arr[0] = m;
        arr[1] = n;
        System.out.println("swap2:" + "m = " + arr[1] + ", n = " + arr[0]);
//        System.out.println(Arrays.toString(arr));
    }
    //正确写法三(易懂)
    public void swap3(int m, int n){
        int temp = m;
        m = n;
        n = temp;
        System.out.println("swap3:" + "m = " + m+ ", n =" + n);
    }
}

你可能感兴趣的:(java)