0
public class Utility {
    public static final <T> void swap(T a, T b) {
        T temp = a;
        a = b;
        b= temp;
    }
    
    public static final <T> void swapArr(T[] arr, int a, int b) {
        T temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }
}

why Utility.swap(a[i], a[j]); won't correctly swap the two element of array, but Utility.swapArr(arr, i, j); works fine?

sxy
  • 61
  • 6
  • 1
    How could `swap(T a, T b)` know which elements to swap? – Bohemian Oct 21 '21 at 04:15
  • @ tgdavies I get java pass the value of a[I] and a[j] to the ```swap``` method, but isn't when ``swap`` method finishes running, it would return the new value to a[I] and a[j]? I guess I just couldn't see where is the difference between this ```swap``` method and a simple a[i] = 9, a[j] = 6. – sxy Oct 21 '21 at 04:17
  • 1
    Passing the *elements* of the array just passes the `int` values - without the context of them being elements in the array. Also, assigning new values to parameters within the method has no effect whatsoever to what was passed in. – Bohemian Oct 21 '21 at 04:19
  • Thank you @Bohemian, I see the issue now. – sxy Oct 21 '21 at 04:36

0 Answers0