【发布时间】:2015-03-30 06:26:02
【问题描述】:
请看以下代码:
public static void main(String[] args)
{
Test t1 = new Test();
t1.i = 1;
Test t0 = t1;
Test t2 = new Test();
t2.i = 2;
t0 = t2;
System.out.println(t1.i); //prints 1, I thought it would print 2
}
在我通过简单的赋值从其他地方获得 t1 对象而不直接访问 t1 后,有什么方法可以更改它? (即 t1 = t0)
【问题讨论】:
-
“在我从其他地方得到 t1 对象后,有没有办法通过简单的赋值而不直接访问 t1 来更改它?”不,您只能使用
=运算符(如reference = otherInstance)重新分配引用,因此如果您想在t1中包含来自t0的实例,您唯一的选择是t1 = t0。
标签: java variable-assignment pass-by-reference