提问人:ayaz husain 提问时间:3/7/2020 最后编辑:Andronicusayaz husain 更新时间:3/14/2020 访问量:74
为什么该方法会更改传递的数组的值
Why does the method change passed array's value
问:
我正在对局部变量进行更改并返回它。我认为它应该在第 12 行打印 9。
public class HackerEarth {
int a[]= {3,4,5};
int b[]=foo(a);
void display() {
System.out.println(a[0]+a[1]+a[2]+ " "); //line no 9
System.out.println(b[0]+b[1]+b[2]+ " ");
}
public static void main(String[] args) {
HackerEarth he=new HackerEarth();
he.display();
}
private int[] foo(int[] a2) {
int b[]=a2;
b[1]=7;
return b;
}
}
任何建议将不胜感激。
答:
1赞
WJS
3/7/2020
#1
因为您要将数组中的第二个值更改为 7。您正在方法中执行此操作。
private int[] foo(int[] a2) {
int b[] = a2; // <-- copying the array reference.
b[1] = 7; // so changing the second value here.
return b;
}
1赞
Andronicus
3/7/2020
#2
您正在使用对第一个数组的引用来覆盖它在方法中的值。若要根据传递的数组的值创建另一个数组,请考虑使用 Arrays.copyOf
:foo
private int[] foo(int[] a2) {
int b[] = Arrays.copyOf(a2, a2.length);
b[1]=7;
return b;
}
1赞
Adnan
3/7/2020
#3
您可以将数组 A 的值分配给数组 B,而不是将数组 A 的值分配给数组 B:int b[] = a2;
private int[] foo(int[] a2) {
int[] b = Arrays.copyOf(a2,a2.length);
b[1]=7;
return b;
}
输出
12
15
评论
0赞
Adnan
3/7/2020
@Andronicus,我没有同时复制现有的答案,而是发布了相同的答案
0赞
Andronicus
3/7/2020
好吧,那就麻烦了;>
上一个:两个对象的两个属性的交换值
评论