Here is the question: write a method that swaps two variables. These two variables should be primitives. It doesn't need to be generic e.g. two int
variables. Is there a way?!
views:
1321answers:
6Without using an array or objects, no, it is not possible to do it within a method.
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.
In java5, the closest I can think of, which may help you, is :
The AtomicInteger class (and others) have getAndSet()
atomic methods ..
As Thomas Owens said. You could probably do it in C by passing variables by &reference, but afaik not in Java without using objects.
To write a swap method that swaps primitives you'd have to have the concept of "out" variables, i.e. variables whose values are passed up to the calling context. C# has those but you must still specify that they're out variables.
You can write method which will return two-elements array which contents are swapped parameters to that method.
static Object[] swap(Object a, Object b) {
return new Object[]{b,a};
}