【问题标题】:Side-Effects Occurring Even When Declaring New Variables in Void Functions即使在 Void 函数中声明新变量时也会发生副作用
【发布时间】: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


    【解决方案1】:
     int[] newNums = nums;  // Declare new array
    

    您已将 nums 引用分配给 newNums。在执行该行之后, nums 和 newNums 都将指向同一个数组,因为它们具有相同的内存引用。当您通过分配 -1 来修改 newNums 数组时,它也会反映到 nums 数组中,因为两者是相同的。
    当您想将 nums 数组克隆到 newNums 数组中时,您可以执行以下操作。

      int [] newNums = nums.clone();
    
    

    这一行会将 nums 数组复制到一个新的内存位置,并且该内存位置将分配给 newNums 数组。

    【讨论】:

    • 哇,有见地!我有这样的想法,但我不确定。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多