【发布时间】:2021-11-13 08:41:26
【问题描述】:
我正在做一个问题,我必须返回输入数组的所有排列,我注意到一些非常奇怪的东西。出于这个问题的目的,我删除了代码中任何令人分心的实际排列部分,以演示我在说什么。以下是代码:
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();
}
代码中有 cmets 可帮助您理解。如果我们输入一个数组 nums [1, 2, 3],我希望 print 方法打印一个未更改的 nums 数组 [1, 2, 3] 1、2、3]。但是,它改为打印带有 -1 的已更改 nums 数组。
我了解 Java 中的 void 方法具有副作用。但是,我的问题是,如果我对名为 的新数组进行修改(将第 i 个元素的值更改为 -1),为什么每个循环末尾的 nums 数组会被更改新数字。
【问题讨论】:
标签: java arrays methods permutation side-effects