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?
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With