use*_*874 0 java arrays println
当我运行此代码时,它会打印0,1,2,但我不知道为什么.你能解释一下吗?
public void run() {
int[] arr = new int [3];
for(int i=0; i<arr.length;i++){
arr[i]=i;
}
domore(arr);
for(int i=0; i<arr.length;i++){
println(arr[i]);
}
}
private void domore(int[] arr) {
// TODO Auto-generated method stub
int [] att = new int [3];
for(int i=0; i<att.length;i++){
att[i]=77;
}
arr=att;
}
Run Code Online (Sandbox Code Playgroud)
在Java中 - "对象的引用按值传递".您在doMore()方法中所做的任何更改都不会反映在原始数组中,因为您正在重新分配传递的引用...(请使用camelCase命名方法/字段.即,使用doMore()而不是domore).
public void run() {
int[] arr = new int [3]; // arr points to an integer array of size 3
doMore(arr);
}
private static void doMore(int[] arrNew) { // arrNew is copy of arr so it also points to the same integer array of size 3. So, any changes made by arrNew are as good as changes made by arr (and yes data of arr is changed..)
// TODO Auto-generated method stub
int [] arrNew = new int [3]; // you are making arrNew point to new integer array of size 3. So, now arrNew points to a new object and not to the one pointed by arr.
for(int i=0; i<arrNew.length;i++){
arrNew[i]=77;
}
}
Run Code Online (Sandbox Code Playgroud)