Search code examples
javaarraysmethodspermutationside-effects

Side-Effects Occurring Even When Declaring New Variables in Void Functions


I was doing a question where I had to return all the permutations of an input array, and I noticed something really peculiar. For the purpose of this question, I removed any distracting, actual permutation parts of the code to demonstrate what I'm talking about. Following is the code:

public List<List<Integer>> permute(int[] nums) {
    permute(nums, 0);
    List<List<Integer>> output = new ArrayList<>();
    return output;
}

// Recursive void function.
private void permute(int[] nums, int index) {
    if (index > nums.length - 1)
        return;
    
    for (int i = 0; i < nums.length; i++) {
        int[] newNums = nums;  // Declare new array
        int newIndex = index;
        newNums[i] = -1;  // Modification on new array. 
        permute(newNums, newIndex + 1);
        print(nums); // Should technically show my "nums" without any side-effect as I've declared a new variable "newNums"
    }
}

// Simple function for printing out an array on the console.
private void print(int[] nums) {
    System.out.print("[");
    for (int num : nums) 
        System.out.print(num + ", ");
    System.out.print("]");
    System.out.println();
}

There are comments in the code to aid in your understanding. If we inputted an array nums of [1, 2, 3], I would expect the print method to print an unchanged nums array of [1, 2, 3]. However, it is instead printing a changed nums array with -1's.

I understand that void methods in Java come with a side-effect. However, my question is why would the nums array at the end of each loop be changed if I made the modifications (change the value at the ith element to -1) on a new array called newNums.


Solution

  •  int[] newNums = nums;  // Declare new array
    

    You have assigned nums reference into the newNums. after execution of that line both nums and newNums will point to the same array because both have same memory reference. As you are modifying newNums array by assigning -1 so it will also be reflect into nums array because both are same.
    As you want to clone the nums array into newNums array then you can do something like below.

      int [] newNums = nums.clone();
    
    

    This line will copy the nums array into a new memory location and that memory location will be assign to newNums array.