小编典典
您的陈述大致相当于这种扩展形式:
x = x ^ (y = y ^ (x = x ^ y));
与C语言不同,在Java中,保证二进制运算符的左操作数在右操作数之前进行求值。评估如下:
x = x ^ (y = y ^ (x = x ^ y))
x = 1 ^ (y = 2 ^ (x = 1 ^ 2))
x = 1 ^ (y = 2 ^ (x = 3))
x = 1 ^ (y = 2 ^ 3) // x is set to 3
x = 1 ^ (y = 1)
x = 1 ^ 1 // y is set to 1
x = 0 // x is set to 0
您可以反转每个xor表达式的参数顺序,以便在再次评估变量之前完成赋值:
x = (y = (x = x ^ y) ^ y) ^ x
x = (y = (x = 1 ^ 2) ^ y) ^ x
x = (y = (x = 3) ^ y) ^ x
x = (y = 3 ^ y) ^ x // x is set to 3
x = (y = 3 ^ 2) ^ x
x = (y = 1) ^ x
x = 1 ^ x // y is set to 1
x = 1 ^ 3
x = 2 // x is set to 2
这是一个更紧凑的版本,也可以使用:
x = (y ^= x ^= y) ^ x;
但这是交换两个变量的真正可怕的方法。使用临时变量是一个更好的主意。
2020-09-16