我正在努力想象为什么这段代码会返回它返回的内容。
public class IntObject
{
private int myInt;
public IntObject() { myInt = 0; }
public IntObject(int n) { myInt = n; }
public void increment() { myInt++; }
}
驱动程序文件
public class IntObjectTest
{
public static IntObject someMethod(IntObject obj) {
IntObject ans = obj;
ans.increment();
return ans;
}
public static void main(String[] args) {
IntObject x = new IntObject(2);
IntObject y = new IntObject(7);
IntObject a = y;
x = someMethod(y);
a = someMethod(x);}
在我脑海里,程序正在进行中 是的 x是y + 1或a + 1,在这种情况下是8 a是x(8)+ 1.所以它是9
当程序结束我认为它们的值是
时x = 8
y = 9
a = 9
但是正确的值都是9.我认为我在使用别名时遇到了麻烦。任何人都可以帮我解释别名以及他们如何在这段代码中工作吗?
答案 0 :(得分:6)
那些不是别名,它们是引用。
IntObject x = new IntObject(2); // <-- 2
IntObject y = new IntObject(7); // <-- 7
IntObject a = y; // <-- 7
x = someMethod(y); // <-- 8
a = someMethod(x); // <-- 9.
致电someMethod
时,
IntObject ans = obj; // ans points to obj.
ans.increment(); // same as obj.increment();
return ans;
我认为你期待
IntObject ans = obj.clone(); // ans points to a copy of obj.
ans.increment(); // now it won't modify obj.
return ans;
答案 1 :(得分:0)
你正在失去x和a的实际参考。
public static void main(String[] args) {
IntObject x = new IntObject(2); // "new" is creating a memory block. lets call it 0x10
IntObject y = new IntObject(7); // another "new" is creating a memory block. lets call it 0x20
IntObject a = y; // here, a = 0x20
x = someMethod(y); //someMethod actually takes an element and give same element. so here, x shows 0x20
a = someMethod(x); //someMethod actually takes an element and give same element. so here, x shows 0x20, then a shows 0x20
// at the and, y does not change anytime. so all objects addressing to 0x20
}
答案 2 :(得分:0)
someMethod(y)返回y,所以x = y;
someMethod(x)返回x,所以a = x;
==&GT;&GT; y = x = a