gpt4 book ai didi

java - 我的程序更改了函数内数组的元素,而无需我显式更改它。这是怎么发生的?

转载 作者:行者123 更新时间:2023-12-03 02:56:40 25 4
gpt4 key购买 nike

所以我正在编写一个函数,它应该交换数组的第一个和最后一个元素并返回修改后的数组。我的代码如下:

public static int[] swapEnds(int[] nums) {

int newArray[] = new int[nums.length];
newArray = nums; // copies all the elements to the new array
newArray[0] = nums[nums.length -1 ]; // changes the first element of the newArray
newArray[newArray.length-1] = nums[0]; // changes the last element of the newArray

return newArray;
}

通过进行一些调试,我发现 nums[0] 已以某种方式更改,但我没有在代码中的任何位置进行更改。任何帮助将非常感激。谢谢。

最佳答案

newArray = nums; // copies all the elements to the new array

不,这不会将元素复制到新数组,而是将原始数组的引用复制到 newArray 变量,这意味着只有一个数组和两个 nums code> 和 newArray 变量指向它。因此,您正在修改原始数组。

使用newArray = Arrays.copyOf(nums,nums.length);创建数组的副本。

编辑:您实际上在这里创建了一个新数组 - int newArray[] = new int[nums.length]; - 但随后您对该数组不执行任何操作。

关于java - 我的程序更改了函数内数组的元素,而无需我显式更改它。这是怎么发生的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31129146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com