为什么该方法会更改传递的数组的值
Why does the method change passed array's value
我正在对局部变量进行更改并将其返回。我认为它应该在第 9 行打印 12。
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;
}
}
如有任何建议,我们将不胜感激。
因为您正在将数组中的第二个值更改为 7。您正在方法中执行此操作。
private int[] foo(int[] a2) {
int b[] = a2; // <-- copying the array reference.
b[1] = 7; // so changing the second value here.
return b;
}
您正在使用对第一个数组的引用来覆盖它在 foo
方法中的值。要根据传递的值创建另一个数组,请考虑使用 Arrays.copyOf
:
private int[] foo(int[] a2) {
int b[] = Arrays.copyOf(a2, a2.length);
b[1]=7;
return b;
}
您可以将数组 a 的值复制到 b,而不是将数组 a int b[] = a2;
的引用分配给数组 b :
private int[] foo(int[] a2) {
int[] b = Arrays.copyOf(a2,a2.length);
b[1]=7;
return b;
}
输出
12
15
我正在对局部变量进行更改并将其返回。我认为它应该在第 9 行打印 12。
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;
}
}
如有任何建议,我们将不胜感激。
因为您正在将数组中的第二个值更改为 7。您正在方法中执行此操作。
private int[] foo(int[] a2) {
int b[] = a2; // <-- copying the array reference.
b[1] = 7; // so changing the second value here.
return b;
}
您正在使用对第一个数组的引用来覆盖它在 foo
方法中的值。要根据传递的值创建另一个数组,请考虑使用 Arrays.copyOf
:
private int[] foo(int[] a2) {
int b[] = Arrays.copyOf(a2, a2.length);
b[1]=7;
return b;
}
您可以将数组 a 的值复制到 b,而不是将数组 a int b[] = a2;
的引用分配给数组 b :
private int[] foo(int[] a2) {
int[] b = Arrays.copyOf(a2,a2.length);
b[1]=7;
return b;
}
输出
12
15