【问题标题】:My program changes the elements of the array inside the function without me changing it explicitly. How does it happen?我的程序更改了函数内部数组的元素,而我没有明确更改它。它是如何发生的?
【发布时间】:2015-06-30 03:45:12
【问题描述】:

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

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] 已经以某种方式更改,但我没有在我的代码中的任何地方进行更改。任何帮助将非常感激。谢谢。

【问题讨论】:

    标签: java arrays function swap


    【解决方案1】:
    newArray = nums; // copies all the elements to the new array
    

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

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

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

    【讨论】:

    • Nitpick: "it copies the reference" 听起来像同一件事,可能是“指向”或类似的东西,但可能是关于“指针”的讨论'不值得避免;)
    • 我试过 newArray = Arrays.copy(nums,nums.length);编译器不喜欢它。
    • @Harry 对不起,它实际上是 copyOf
    • 现在完美运行。谢谢!但是是的,我仍然需要一些关于指针/参考的帮助。你能推荐任何文章吗?专门用于数组
    • @Harry 只需阅读任何 Java 书籍/教程。也许这个 - docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
    猜你喜欢
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    相关资源
    最近更新 更多