代码: package puzz; public class CleverSwap { public static void main(String[] args) { swap1(); swap2(); swap3(); swap4(); } // wrong method public static void swap1() { int x = 1986; int y = 2010; x ^= y ^= x ^= y; System.out.println("x = " + x); System.out.println("y = " + y); System.out.println("--------------------"); } // this method will work,but do not do this public static void swap2() { int x = 1986; int y = 2010; y = (x ^= (y ^= x)) ^ y; System.out.println("x = " + x); System.out.println("y = " + y); System.out.println("--------------------"); } // this method will work,but do not do this public static void swap3() { int x = 1986; int y = 2010; x ^= y; y ^= x; x ^= y; System.out.println("x = " + x); System.out.println("y = " + y); System.out.println("--------------------"); } // OK public static void swap4() { int x = 1986; int y = 2010; int temp; temp = x; x = y; y = temp; System.out.println("x = " + x); System.out.println("y = " + y); System.out.println("--------------------"); } } 输出: //x = 0 //y = 1986 //-------------------- //x = 2010 //y = 1986 //-------------------- //x = 2010 //y = 1986 //-------------------- //x = 2010 //y = 1986 //-------------------- 在单个表达式中不要对相同变量赋值多次 避免所谓的聪明的编程技巧,保证代码意图明确