It is possible to use an auxiliary function like this:
int returnFirst(int x, int y) {
return x;
}
int a = 8, b = 3;
a = returnFirst(b, b = a); // Leia como a = b; b = a;
System.out.println("a: " + a + ", b: " + b); // prints a: 3, b: 8
Using the returnFirst function, we have a solution that meets almost all requirements:
- The exchange of values is done in only one statement;
- No need to declare a temporary variable (does not pollute caller code);
- Does not allocate temporary objects;
- With some overloads, being one of them with a Generic
<T>
, works for any type;
- The implementation of the auxiliary is trivial;
- Does not use tricks that only work integer numbers (such as XOR).
The specification of the Java language (Java Language Specification, Java SE 7 Edition, section 15.12.4.2) ensures that the value of b is evaluated and passed before being overwritten by the assignment b = a in the second argument, unlike other languages (as I recall, C and C++ are not at all friendly and do not guarantee any order of evaluation of the arguments, only ensure that they will all be evaluated before the function starts to perform, obviously).
If you choose a short name like r1
, is very easy to read
a = r1(b, b = a);
as if it were
a = b; b = a;
(although in fact b = a
perform first)
"it is impossible to make a method
swap
in Java" It is good to clarify: impossible in the sense of the method - as a side effect - make the value ofa
go to the address/pointer/reference ofb
and vice versa. Because the only way to assign a simple reference in Java is through an operator in the very context of the method where it is declared.– mgibsonbr
@mgibsonbr, well noted, in case it is impossible to make a
swap
the traditional way (using the values passed as reference). I will edit the answer to make it more appropriate.– Felipe Avelar