While it is not possible to write a function that simply swaps two variables, it is possible to write a helper function that allows you to:
- Swap two variables using only one statement
- Without temporary variables in the caller's code
- Without 'boxing' primitives
- With a few overloads (one of them using generics), it works for any type
That's how you could do it:
int returnFirst(int x, int y) {
return x;
}
int a = 8, b = 3;
a = returnFirst(b, b = a); // try reading this as a = b; b = a;
System.out.println("a: " + a + ", b: " + b); // prints a: 3, b: 8
This works because the Java language guarantees (Java Language Specification, Java SE 7 Edition, section 15.12.4.2) that all arguments are evaluated from left to right (unlike some other languages, where the order of evaluation is undefined), so the execution order is:
- The original value of
b
is evaluated in order to be passed as the first argument to the function
- The expression
b = a
is evaluated, and the result (the new value of b
) is passed as the second argument to the function
- The function executes, returning the original value of
b
and ignoring its new value
- You assign the result to
a
If returnFirst
is too long, you can choose a shorter name to make code more compact (e.g. a = sw(b, b = a)
). Use this to impress your friends and confuse your enemies :-)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…