有人可以解释一下这个程序是如何执行的吗?
这是我似乎不太明白其输出的代码:
class Box {
int size;
Box (int s) {
size = s;
}
}
public class Laser {
public static void main(String[] args) {
Box b1 = new Box(5);
Box[] ba = go(b1, new Box(6));
ba[0] = b1;
for(Box b : ba)
System.out.println(b.size + " ");
}
static Box[] go (Box b1, Box b2) {
b1.size = 4;
Box[] ma = {b2, b1};
return ma;
}
}
我运行时的实际输出是 4, 4。但根据我的理解,这应该是 5, 4。 任何人都可以帮助理解这是如何执行的吗?
最佳答案
我已经为你添加了评论;
The important TWIST that you missed here is;
Box[] ma = {b2, b1};
它不是 {b1,b2}
。返回时内存位置会互换。
public static void main(String[] args) {
Box b1 = new Box(5); // b1 == location A
Box[] ba = go(b1, new Box(6)); // ba == location B which stores Location A, D
// PLEASE NOTE HERE
// After the function go() is executed;
// ba[] will have {D, A}
// So ba[0] will have object b1 which is at location A.
ba[0] = b1; // location B will now store A and A
for(Box b : ba)
System.out.println(b.size + " "); // Output: 4 and 4
}
static Box[] go (Box b1, Box b2) { // go(location A, location D )
b1.size = 4; // A's object.size = 4
Box[] ma = {b2, b1}; // position is interchanged here (D and A)
return ma; // return the location of ma
}
希望这有帮助。
如果您有任何疑问,请告诉我。 java中一切都是按值传递的。内存地址按值传递。
关于java - 按引用调用或按值调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18213305/