Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to write swap method in Java? [duplicate]

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?!

like image 970
Khaled Alshaya Avatar asked Sep 01 '09 15:09

Khaled Alshaya


People also ask

How do you swap multiple variables in Java?

Two variables can be swapped in one line in Java. This is done by using the given statement. x = x ^ y ^ (y = x); where x and y are the 2 variables.

How do you swap two items in an ArrayList?

In order to swap elements of ArrayList with Java collections, we need to use the Collections. swap() method. It swaps the elements at the specified positions in the list.


1 Answers

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:

  1. The original value of b is evaluated in order to be passed as the first argument to the function
  2. The expression b = a is evaluated, and the result (the new value of b) is passed as the second argument to the function
  3. The function executes, returning the original value of b and ignoring its new value
  4. 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 :-)

like image 104
marcus Avatar answered Sep 23 '22 14:09

marcus