gpt4 book ai didi

java - 为什么 "a^=b^=a^=b;"与 "a^=b; b^=a; a^=b;"不同?

转载 作者:IT老高 更新时间:2023-10-28 20:49:38 28 4
gpt4 key购买 nike

我尝试了一些代码来交换 Java 中的两个整数,而不使用第三个变量,使用 XOR。

这是我尝试过的两个交换函数:

package lang.numeric;

public class SwapVarsDemo {

public static void main(String[] args) {
int a = 2984;
int b = 87593;
swapDemo1(a,b);
swapDemo2(a,b);
}

private static void swapDemo1(int a, int b) {
a^=b^=a^=b;
System.out.println("After swap: "+a+","+b);
}

private static void swapDemo2(int a, int b) {
a^=b;
b^=a;
a^=b;
System.out.println("After swap: "+a+","+b);
}

}

这段代码产生的输出是这样的:

After swap: 0,2984
After swap: 87593,2984

我很想知道,为什么会有这样的说法:

        a^=b^=a^=b;

和这个不一样?

        a^=b;
b^=a;
a^=b;

最佳答案

问题是评估的顺序:

JLS section 15.26.2

First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs.

Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion (§5.1.13) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.

所以你的表达方式是:

a^=b^=a^=b;

  1. 评估 a
  2. 评估 b^=a^=b
  3. xor 两者(所以第一步中的 a 还没有应用 ^=b)
  4. 将结果存储在 a

也就是说,你的表达式等价于下面的java代码:

    int a1 = a;
int b2 = b;
int a3 = a;
a = a3 ^ b;
b = b2 ^ a;
a = a1 ^ b;

你可以从你的方法的反汇编版本中看到:

  private static void swapDemo1(int, int);
Code:
0: iload_0
1: iload_1
2: iload_0
3: iload_1
4: ixor
5: dup
6: istore_0
7: ixor
8: dup
9: istore_1
10: ixor
11: istore_0

关于java - 为什么 "a^=b^=a^=b;"与 "a^=b; b^=a; a^=b;"不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22044163/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com