第一次
public static void main(String[] args) {
int x = 5,y = 4;
y ^= x ^= y;
System.out.println("all "+x +" " + y);
int a = 5,b = 4;
a^=b;
System.out.println("first "+a +" " + b);
b^=a;
System.out.println("second "+a +" " + b);
}
编译后结果
all 1 5
first 1 4
second 1 5
第二次
public static void main(String[] args) {
int x = 5,y = 4;
x^=y ^= x ^= y;
System.out.println("all "+x +" " + y);
int a = 5,b = 4;
a^=b;
System.out.println("first "+a +" " + b);
b^=a;
System.out.println("second "+a +" " + b);
a^=b;
System.out.println("Third "+a +" " + b);
}
编译结果
all 0 5
first 1 4
second 1 5
Third 4 5
public static void main(String[] args) {
int x = 5,y = 4;
y ^= x ^= y;
System.out.println("all "+x +" " + y);
int a = 5,b = 4;
a^=b;
System.out.println("first "+a +" " + b);
b^=a;
System.out.println("second "+a +" " + b);
}
编译后结果
all 1 5
first 1 4
second 1 5
第二次
public static void main(String[] args) {
int x = 5,y = 4;
x^=y ^= x ^= y;
System.out.println("all "+x +" " + y);
int a = 5,b = 4;
a^=b;
System.out.println("first "+a +" " + b);
b^=a;
System.out.println("second "+a +" " + b);
a^=b;
System.out.println("Third "+a +" " + b);
}
编译结果
all 0 5
first 1 4
second 1 5
Third 4 5
这样做是不正确的。
跟java 的表达式提取规则有关。
推荐参考一下The Java Puzzlers这本书吧
上面讲的很详细,我就没有必要再写一遍了。
推荐你看一下我说的那本书,上面有这个例子。
最好自己动手,看看bytecode怎么回事。
public class CleverSwap { public static void main(String[] args) { int x = 1984; // (0x7c0) int y = 2001; // (0x7d1) x ^= y ^= x ^= y; System.out.println("x = " + x + "; y = " + y); }}
// The actual behavior of x ^= y ^= x ^= y in Javaint tmp1 = x; // First appearance of x in the expressionint tmp2 = y; // First appearance of yint tmp3 = x ^ y; // Compute x ^ yx = tmp3; // Last assignment: Store x ^ y in xy = tmp2 ^ tmp3; // 2nd assignment: Store original x value in yx = tmp1 ^ y; // First assignment: Store 0 in x