While it is impossible to write a function that simply swaps two variables, you can write an auxiliary function that allows you to:
- Exchange two variables with just one operator
- No temporary variables in caller code
- No primitives <boxes>
- With multiple overloads (one of them uses generics), it works for any type
How could you do this:
int returnFirst(int x, int y) { return x; } int a = 8, b = 3; a = returnFirst(b, b = a);
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 evaluation order is undefined), so the order of execution:
- The initial value of
b is evaluated to be passed as the first argument to the function - The expression
b = a expressed, and the result (the new value of b ) is passed as the second argument to the function - The function executes by returning the original value of
b and ignoring its new value - You assign the result
a
If returnFirst too long, you can choose a shorter name to make the code more compact (e.g. a = sw(b, b = a) ). Use this to impress your friends and confuse your enemies :-)
marcus May 30 '13 at 0:59 2013-05-30 00:59
source share