Every time I want to swap two values I have to use temporary to do the actual swap. Why doesn't Java give us a facility method in whatever class to simply swap the values of two vars?
Asked
Active
Viewed 3,339 times
4
-
4So what's the question? why Java haven't something for that? Ask java creators. – shift66 Mar 01 '12 at 11:06
-
See http://stackoverflow.com/questions/3624525/how-to-write-a-basic-swap-function-in-java and http://stackoverflow.com/questions/2393906/how-do-i-make-my-swap-function-in-java – David Heffernan Mar 01 '12 at 11:10
-
@Ademiban correct your grammar. – Juvanis Mar 01 '12 at 11:10
-
4Can't remember the last time I actually had to swap values in real code... (except from code snippets posted to SO ;) ) – Andreas Dolk Mar 01 '12 at 11:12
-
1@Andreas_D - one could argue that the reason you can't remember is that you are subconsciously dismissing "solutions" that would require `swap`. :-) – Stephen C Mar 01 '12 at 11:28
2 Answers
11
Java is Pass-by-Value. That is why you cannot create a simple swap-method (ref).
You can however wrap your references inside another object and swap the internal refs:
public static void main(String[] args) {
Ref<Integer> a = new Ref<Integer>(1);
Ref<Integer> b = new Ref<Integer>(2);
swap(a, b);
System.out.println(a + " " + b); // prints "2 1"
}
public static <T> void swap(Ref<T> a, Ref<T> b) {
T tmp = a.value;
a.value = b.value;
b.value = tmp;
}
static class Ref<T> {
public T value;
public Ref(T t) {
this.value = t;
}
@Override
public String toString() {
return value.toString();
}
}

dacwe
- 43,066
- 12
- 116
- 140
3
Java does not supply such method because it is not possible. Variables are passed to method by value. Yes, even if these are objects. In this case we pass reference to object by value. Therefore you cannot change value of source variable inside method that received this variable as parameter:
int a = 5;
int b = 6;
swap(a, b);
// a is still 5, b is still 6!
void swap(int first, int second) {
int tmp = first;
first = second;
second = tmp;
}

AlexR
- 114,158
- 16
- 130
- 208
-
As mentioned elsewhere, this can be easily accomplished by wrapping the values to be swapped inside an object. – David Bandel Oct 16 '20 at 22:41