可能重复:
异或变量交换如何工作?
我找到了一个在不创建第三个变量的情况下
切换两个变量的值的解决方案,如下:
x ^= y;
y ^= x;
x ^= y;
这是以布尔以外的方式使用异或运算符(“XOR”)(我假设它是按位的?)。最近学习了一些离散数学,我可以理解 XOR 运算符与真值表的用法:
.......................
x y (x XOR y)
.......................
T T F
T F T
F T T
F F F
当两个变量相等时,表达式的(x XOR y)
计算结果为假,否则为真。但是当值不是布尔值时WTF?
无论如何,如果我将 x 和 y 设置为int值而不是布尔值,则操作不是很简单。因此,例如 let
x = 3
和y = 5
:
public class SwitchValues
{
// instance methods
public void SwitchBoolean(boolean x, boolean y)
{
System.out.println("The variable \"x\" is initially: " + x + ".\n" +
"The variable \"y\" is initially: " + y + ".");
x ^= y;
System.out.println("x ^= y is equal to: " + x + ".");
y ^= x;
System.out.println("y ^= x is equal to: " + y + ".");
x ^= y;
System.out.println("x ^= y is now equal to: " + x + ".");
System.out.println("The variable \"x\" is now: " + x + ".\n" +
"The variable \"y\" is now: " + y + ".\n");
} // end of SwitchBoolean
public void SwitchInts(int x, int y)
{
System.out.println("The variable \"x\" is initially: " + x + ".\n" +
"The variable \"y\" is initially: " + y + ".");
x ^= y;
System.out.println("x ^= y is equal to: " + x + ".");
y ^= x;
System.out.println("y ^= x is equal to: " + y + ".");
x ^= y;
System.out.println("x ^= y is now equal to: " + x + ".");
System.out.println("The variable \"x\" is now: " + x + ".\n" +
"The variable \"y\" is now: " + y + ".\n");
} // end of SwitchInts
// main method
public static void main(String[] args)
{
SwitchValues obj = new SwitchValues();
obj.SwitchBoolean(true, false);
obj.SwitchInts(3, 5);
} // end of main method
} // end of class SwitchValues
...并且为 int 值打印的结果如下:
The variable "x" is initially: 3.
The variable "y" is initially: 5.
x ^= y is equal to: 6.
y ^= x is equal to: 3.
x ^= y is now equal to: 5.
The variable "x" is now: 5.
The variable "y" is now: 3.