作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我正在编写一个函数,它应该交换数组的第一个和最后一个元素并返回修改后的数组。我的代码如下:
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/
我是一名优秀的程序员,十分优秀!