【问题标题】:When assigning an int array to another int array variable, if we perform Arrays.sort on the new array variable, does it affect the original int array? [duplicate]将一个int数组赋值给另一个int数组变量时,如果我们对新的数组变量执行Arrays.sort,会不会影响原来的int数组? [复制]
【发布时间】:2021-05-28 10:10:19
【问题描述】:

这是我指的代码块:

public class ExtraCandies
{
    public static void main(String[] args)
    {
        int[] candies = {2,3,5,1,3};

        int temp = 0;
        List<Boolean> isGreatestPossibleList = new ArrayList<>();
        int[] tempArray = candies;

        Arrays.sort(tempArray);

        //Here the debugger shows both tempArray and candies array as sorted.
    }
}

当我调试这段代码时,我发现 tempArray 得到了很好的排序。 tempArray 变为 {1,2,3,3,5}。但调试器现在还显示糖果数组已排序。我很困惑这怎么可能? sort 方法不应该只对这里的 tempArray 进行排序吗?

【问题讨论】:

  • 简短的回答是肯定的。它确实会影响“原始”数组,因为您复制的是数组 reference 而不是数组。
  • 我有一个 dup-close 这个问题作为一个问题的副本,该问题解释了将一个数组变量分配给另一个数组变量的实际作用。您所看到的是直接后果。

标签: java arrays sorting oop


【解决方案1】:

将一个数组分配给另一个数组实际上并没有复制它 - 您只是将原始数组的引用设置为新数组。对数组进行排序意味着对引用进行排序,从而对两个数组进行排序。

您需要使用for 循环或Arrays.copyOf(array, length)

public class ExtraCandies
{
    public static void main(String[] args)
    {
        int[] candies = {2,3,5,1,3};

        int temp = 0;
        List<Boolean> isGreatestPossibleList = new ArrayList<>();
        int[] tempArray = Arrays.copyOf(candies, candies.length);

        Arrays.sort(tempArray);

        //Here the debugger shows both tempArray and candies array as sorted.
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 2014-02-15
    相关资源
    最近更新 更多