谁能向我解释为什么这段代码的输出如下?
0 40
0 40
public class Class extends Main {
public static void main(String[] args) {
int x = 0;
int [] arr = {20};
f (x, arr);
System.out.println(x + " " + arr[0]);
g (x, arr);
System.out.println(x + " " + arr[0]);
}
public static void f(int x, int[] arr) {
x += 30;
arr[0] = 40;
}
public static void g(int x, int[] arr) {
x = 50;
arr = new int[] {60};
}
}
我认为应该是这样的:
0 20
0 20
最佳答案
数组是一个对象,因此当您将其传递给方法时,您将传递对该对象的引用。因此,方法调用可以更改数组中的元素,并且更改后的数组与传递给方法的数组相同。因此,f()
的调用者会看到这些更改。
另一方面,当您将原始值传递给方法时,将创建变量的副本,并且该方法所做的任何更改都属于该方法的范围。当该方法接收到一个包含对象引用的变量并尝试为其分配新引用时,也是如此。该分配是该方法的本地方法。这就是为什么g()
不会更改传递给它的数组的原因。
关于java - 无法找到此Java代码的输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26955829/