Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Java doesn't supply a simple swap function? [closed]

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?

like image 373
Jackson Tale Avatar asked Dec 10 '22 02:12

Jackson Tale


1 Answers

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();
    }
}
like image 160
dacwe Avatar answered Dec 25 '22 22:12

dacwe