我的程序更改了函数内部数组的元素,而没有显式更改它.怎么会发生?

Har*_*uri 2 java arrays swap function

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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

Era*_*ran 6

newArray = nums; // copies all the elements to the new array
Run Code Online (Sandbox Code Playgroud)

不,这不会将元素复制到新数组,它会将原始数组的引用复制到newArray变量,这意味着只有一个数组,nums并且newArray变量都指向它.因此,您正在修改原始数组.

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

编辑:你实际上在这里创建一个新数组int newArray[] = new int[nums.length];- 但是你对这个数组什么都不做.