Javaの本質を透析する-変数を交換するいくつかの方式

1730 ワード

package com.java.essence_36;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by lw on 14-5-18.
 * <p/>
 *          
 */
public class Replace {

    //    -    
    private static void temp_Replace(V v) {
        int temp = v.a;
        v.a = v.b;
        v.b = temp;
        System.out.println("temp_Replace(V v)->" + v);
    }

    //    —  
    private static void add_temp_Replace(V v) {
        int temp = v.a + v.b;
        v.a = temp - v.a;
        v.b = temp - v.b;
        System.out.println("add_temp_Replace(V v)->" + v);
    }

    //    -  
    private static void sub_temp_Replace(V v) {
        int temp = v.a - v.b;
        v.a = v.a - temp;
        v.b = v.b + temp;

        System.out.println("sub_temp_Replace(V v)->" + v);
    }

    //    , a=a^b^b;
    private static void yihuo_Replace(V v) {
        v.a = v.a ^ v.b;
        v.b = v.a ^ v.b;
        v.a = v.a ^ v.b;
        System.out.println("yihuo_Replace(V v)->" + v);
    }


    public static void main(String[] args){
        temp_Replace(new V(1, 2));
        add_temp_Replace(new V(1, 2));
        sub_temp_Replace(new V(1, 2));
        yihuo_Replace(new V(1, 2));

    }


}

class V {
    int a, b;

    V(int a, int b) {
        this.a = a;
        this.b = b;
        System.out.println("   -V{" +
                "a=" + a +
                ", b=" + b +
                '}');
    }

    @Override
    public String toString() {
        return "   -V{" +
                "a=" + a +
                ", b=" + b +
                '}';
    }
}