Java交换值及中间缓存机制


实现交换int a,b的值的函数,C++可以采用引用或指针传递的方法,当Java不行;
因为Java的参数传递机制与C++不同( http://blog.youkuaiyun.com/woliuyunyicai/article/details/44096043),
如下方法均不能够实现:
public void swap(int x, int y)
{
    int temp = x;
    x = y;
    y = x;
}
 
 public void swap(Integer x, Integer y)
 {
    Integer temp = x;
    x = y;
    y = x;
 }
不使用中间变量,方法有:
 异或
  y = x ^ y;
  x = x ^ y;
  y = x ^ y;
加法:
  x = x + y;
  y = x - y;
  x = x - y;
运算:(利用Java的变量缓存机制)
  x = y + 0 * (y = x);



Java变量缓存机制:(注意基本运算与C++的区别)http://blog.youkuaiyun.com/woliuyunyicai/article/details/40378031
public class Main1 {
 
    public static void main(String args[]) {   
        int a, b;
        a = 5; b = 8;
        a = b * 3 + (b = a) * 2 + (b = 7);
//      System.out.printf("%d,%d",a, a + (0 * (a = b)) );注意Java的Printf也与C++参数入栈方式不同,
C++一般函数压栈是从右到左,构造函数初始化列表从左到右初始化;
    }
}

从字节码层面进行解释:
-javap:
                                                                                                                                                              当前栈中数据,栈顶在前

       0: iconst_5          常量5压入栈顶                     5

       1: istore_1          弹出常量5,赋值给aa压入栈顶          a

       2: bipush    8       常量8压入栈顶                     8,a

       4: istore_2          弹出常量8赋值给b,b压入栈顶            b,a

       5: iload_2           b推到栈顶                        b,a

       6: iconst_3          常量3压入栈顶                     3,b,a

       7: imul              相乘3*b,结果temp1压入栈顶            temp1,a

       8: iload_1           a推到栈顶                       a,temp1

       9: dup               弹出a,复制aA压到栈顶               A,temp1

      10: istore_2          弹出A,赋值给bb压到栈顶             b,temp1

      11: iconst_2          常量2压入栈顶                     2,b,temp1

      12: imul              弹出2,b;2 * b,结果temp2压入栈顶        temp2,temp1

      13: iadd              双操作数,弹出temp1temp2,           temp2+temp1

                           计算temp1+temp2压入栈顶

      14: bipush   7        常量7压入栈顶                     7,temp2+temp1

      16: dup               弹出7,复制常量7,压入栈顶             7,temp2+temp1

      17: istore_2          弹出7,赋值给bb压入栈顶             b,temp2+temp1

      18: iadd              temp1+temp2+b,结果result压入栈顶       result= b + temp2 + temp1

      19: istore_1          result弹出,赋值给a                      a

      20: return            return


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值