透析Java本质-交换变量的几种方式

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 +
                '}';
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值