Is it possible to write swap method in Java? [duplicate]
Solution 1:
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 ofb
) 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 :-)
Solution 2:
Without using an array or objects, no, it is not possible to do it within a method.
Solution 3:
Check out this JavaWorld article that explains it in detail:
http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
A swap of two primitives will never work because primitives are passed by value in Java. You can't even write a method to swap two objects for that matter.
Like @Thomas said, the only thing you could do is have your primitives contained within other objects/arrays and modify those.
Solution 4:
One-liner for any primitive numbers:
a += (b - (b = a));
Solution 5:
You can make a generic version of @marcus's swap method that swaps any number of objects of the same type:
<T> T swap(T... args) { // usage: z = swap(a, a=b, b=c, ... y=z);
return args[0];
}
b = swap(a, a=b);
z = swap(x, x=y, y=z);