public class test {
public static void main(String[] args){
test t = new test();
int[] A = {1,2,3};
t.change(A);
System.out.println(A[0]+" "+A[1]+" "+A[2]);
}
void change(int[] A){
int[] B = {1,1,1};
A=B; // 1
A= null; // 2
A[0] = 3; // 3
}
}
上面代码情况1输出[1,2,3],情况2输出[1,2,3],情况3输出[3,2,3],数组传递应该传引用才是啊,所以我觉得只有情况3才是正常的。不明白为什么情况1,2不改变数组A
------解决方案--------------------
A=xxx
这种形式是给A这个局部变量赋值,并没有修改引用。
------解决方案--------------------
因为1、2中改变的A根本就不是你main方法中的A
只是A的一份复制品,它和A指向同一个地址,所以3中改变它指向的数组也会改变原数组,因为是同一个嘛
但是你改变A的复制品的地址值,对本来的A是没有影响的