【发布时间】:2018-05-25 02:13:11
【问题描述】:
我知道这个问题显然有很多重复项,例如 here 和 here。
不过我的问题不同。
考虑以下示例:
public class MyClass {
public static void test(int a, int b) {
System.out.println("In test() at start: "+a+" "+b);
int temp=a;
a=b;
b=temp;
System.out.println("In test() at end: "+a+" "+b);
}
public static void main(String args[]) {
int a=1, b=2;
System.out.println("a: "+a+" b: "+b);
test(a, b);
System.out.println("a: "+a+" b: "+b);
}
}
The output that I get对于上面的sn-p是:
a:1 b:2
在开始时的 test() 中:1 2
在最后的 test() 中:2 1
a: 1 b: 2
这表明当我调用 test() 时,main() 中 a 和 b 的原始值没有被交换,因此暗示(如果我理解正确的话)它是按值传递。
现在,考虑以下代码 sn-p:
public class MyClass {
public static void test(int[] arr) {
System.out.println(arr[2]);
arr[2]=20;
System.out.println(arr[2]);
}
public static void main(String args[]) {
int[] arr={0,1,2,3,4,5};
System.out.println(arr[2]);
test(arr);
System.out.println(arr[2]);
}
}
The output that I get 这个代码 sn-p 是:
2
2
20
20
这表明arr[2] 的值在main() 的原始数组中发生了更改,从而表示(如果我理解正确的话)数组是通过引用传递的。
有人可以指出发生了什么吗?为什么会表现出不同的行为?
谢谢!
【问题讨论】:
-
所有数组都是通过引用传递的,默认情况下变量是按值传递的。如果你使用
Integer,它的行为会类似 -
我来自 C++ 背景。所以,如果有人从那个角度来解释,那对我会很有帮助。
-
@Mitchel0022,好的,明白了。
Integer是变量或数组元素的数据类型,你的意思是? -
要么,
Integer是一个对象,因此它将通过引用传递,并且在函数中更改它会永久更改它。int只会改变函数的作用域 -
@Mitchel0022,好的。总而言之,数组和对象是通过引用传递的;其他一切都按价值计算。容器呢?我想再次引用(因为它们只包含对象)?
标签: java pass-by-reference pass-by-value