Why swapping integer variable by XOR doesn't work in a single line?

后端 未结 5 2071
逝去的感伤
逝去的感伤 2020-12-16 17:59

I want to swap the value of two integer variables in java using the XOR operator.

This is my code:

int i = 24;
int j = 17;

i ^= j;
j ^= i;
i ^= j;

         


        
5条回答
  •  一整个雨季
    2020-12-16 18:33

    By writing your swap all in one statement, you are relying on side effects of the inner i ^= j expression relative to the outer i ^= (...) expression.

    From the Java specificiation (15.26 Assignment Operators):

    There are 12 assignment operators; all are syntactically right-associative (they group right-to-left). Thus, a=b=c means a=(b=c), which assigns the value of c to b and then assigns the value of b to a.

    [...]

    AssignmentOperator: one of = *= /= %= += -= <<= >>= >>>= &= ^= |=

    You might want to consider the readability of the code. Perhaps it's best to e.g. put the code in a method called swap(), or do the actual swapping through the use of a temp variable:

    int temp = i;
    i = j;
    j = temp;
    

提交回复
热议问题