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.