1

Possible Duplicate:
How to write a basic swap function in Java

Hi. I don't know java at all, and in the near future have no wish to study it. However I have lots of friends that are java programmers and from conversations I learnt that there is no analog of C#'s ref keyword in Java. Which made me wonder how can one write a function that swaps two integers in Java. My friends (though not very good java experts) could not write such a function. Is it officially impossible? Please note, that I understand that one can swap two integers without a function, the question is exactly to write a function that takes two integers and swaps them. Thanks in advance.

Community
  • 1
  • 1
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434

2 Answers2

4

Short: You can't.

Long: You need some workaround, like wrapping them in a mutable datatype, e.g. array, e.g.:

public static void swap(int[] a, int[] b) {
    int t = a[0]; a[0] = b[0]; b[0] = t;
}

but that doesn't have the same semantic, since what you're swapping is actually the array members, not the a and b themselves.

Lie Ryan
  • 62,238
  • 13
  • 100
  • 144
4

In Java, all the arguments are passed by value. So there is no such thing as a ref.

However, you might achieve variable swapping by wapping values in objects (or arrays).

public class Holder<T> {
  public T value = null;
  public Holder(T v) { this.value = v; }
}

public static <T> void swap(Holder<T> a, Holder<T> b) {
  T temp = a.value; a.value = b.value; b.value = temp;
}
Kru
  • 4,195
  • 24
  • 31