gpt4 book ai didi

java - 为什么下面的程序打印不同数组的对象?

转载 作者:太空宇宙 更新时间:2023-11-04 12:32:06 25 4
gpt4 key购买 nike

我无法理解屏幕后面发生的内部工作,但我很困惑,因为它在控制台中打印的结果与预期的不同。有人可以通过良好的解释来解决我的问题吗?

public class Demo {

public int [] sort(int h[])
{
int temp;
for(int i=0;i<h.length;i++)
{
for (int j=i;j<h.length;j++)
{
if(h[i]>h[j])
{
temp=h[i];
h[i]=h[j];
h[j]=temp;
}

}
}
return h;
}
public static void main(String args[])
{
Demo obj =new Demo();
int a[]={9,2,3,5,32,1,5,3,7};

int[] sorted=obj.sort(a);

/*Code to Display Array a*/
for(int s :a)
{
System.out.print(s+ " ");
}

System.out.println("");


/*Code to Display Array sorted*/
for(int k:sorted)
{
System.out.print(k+" ");
}
}

/*
Expected output
9 2 3 5 32 1 5 3 7
1 2 3 3 5 5 7 9 32

Actual output
1 2 3 3 5 5 7 9 32
1 2 3 3 5 5 7 9 32
*/


}

最佳答案

sort 方法正在处理通过引用调用传递给该方法的实际输入参数(我知道这在措辞方面不是 100% 正确 - 请参阅 here )。也就是说,sort 中对数组 h 的所有更改在调用代码中也可见。

如果不想更改输入参数,则需要复制该对象。在您的情况下,您可以使用 System.arrayCopy 来执行此操作。

关于java - 为什么下面的程序打印不同数组的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37760620/

25 4 0
文章推荐: java - 将主类值存储在子类中作为数组
文章推荐: javascript - 如何禁用 Iframe 内的右键单击
文章推荐: c++ - 在剪辑中复制环境的构造函数?
文章推荐: javascript - 使所有
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com