sammy333
sammy333

Reputation: 1445

Why my swap function works?

As far as I know, Java is passed by value, i.e. when I work with primitive types I can not swap them (if I worked with Objects, however it would be possible). I wrote a program to write down all permutations of an array of integers. To do this I use a swap functions that takes as parameters array, two positions, and swap the numbers in these positions. And my program work?! Can somebody explain me why? Below is the code:

public class Solution {
    public List<List<Integer>> permute(int[] num) {
        if(num == null || num.length == 0)
            return null;
        List<List<Integer>> res = new ArrayList<List<Integer>>();    
        doPermute(num, 0, res);  
        return res;
    }
    public static void doPermute(int[] num, int k, List<List<Integer>> res){
        if(k == num.length){
            res.add(convertArrayToList(num));
            return;
        }
        for(int i = k; i < num.length; i++){
            swap(num, i, k);
            doPermute(num, k+1, res);
            swap(num, k, i);
        }
    }
    public static List<Integer> convertArrayToList(int[] num){
        List<Integer> res = new ArrayList<Integer>();
        for(int i = 0; i < num.length; i++){
            res.add(num[i]);
        }
        return res;
    }
    public static void swap(int[] num, int i, int j){
        int temp = num[i];
        num[i] = num[j];
        num[j] = temp;
    }
}

Upvotes: 2

Views: 154

Answers (2)

Kumar Abhinav
Kumar Abhinav

Reputation: 6675

This will work because you are passing the reference of the Object which you are changing,in your case int[].Note that int[] is also an Object.If you just pass the values of array and then try to change it ,it would have been of no use.Consider this

//Of little use ,the caller Object is not affected in any way
public static void swap(int i, int j){
      int temp = i
      i = j;
      j = i;
    }  

 swap(num[k], num[i]); //invoking of swap method,caller Object reference is not passed,just assignment of parameter value takes place

Since,you have the reference of mutable array Object which you are changing,there is no problem

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201439

Java is pass by value. The value of an Object is a reference address. An array (even an int[]) is an Object. So,

public static void swap(int[] num, int i, int j){
  int temp = num[i];
  num[i] = num[j];
  num[j] = temp;
}

the array num is modifiable in swap. If you look at java.lang.reflect.Array you will notice the methods take an Object array.

Upvotes: 1

Related Questions