简体   繁体   English

Java - 创建对同一对象的两个引用

[英]Java - Creating Two References to the Same Object

Examine the following code: 检查以下代码:

Object object = new Object();
objectList.add(object);
objectListTwo.add(object);

Is there any way to get both arrays to point to the same object, such that when I change object in one array, it changes in the other? 有没有办法让两个数组都指向同一个对象,这样当我在一个数组中更改object时,它会在另一个数组中发生变化?

Thanks for your help! 谢谢你的帮助!

EDIT: Turns, out my above code does exactly that. 编辑:转,我的上面的代码完全是这样。 Problem was elsewhere in my code. 问题在我的代码中的其他地方。 My apologies for my confusion... 我为我的困惑道歉...

Both Lists point to the same Object. 两个列表都指向同一个对象。 Java is passing a reference to the object (by value). Java正在传递对象的引用(按值)。

Depends what you mean by "change." 取决于“改变”的意思。 If you mean change as in calling setters and mutating the object, then those changes are observed. 如果你的意思是在调用setter并改变对象时进行更改,则会观察到这些更改。 If you mean change as in completely reassigning or overwriting the variable (or reference), those changes are not observed. 如果您的意思是在完全重新分配或覆盖变量(或引用)时进行更改,则不会观察到这些更改。

Put it simpler, say you have one object, one array. 更简单,说你有一个对象,一个数组。

Foo foo = new Foo();
Foo[] foos = new Foo[1];
foos[0] = foo;

The item in the array and the variable each reference the same Foo. 数组中的项和变量各引用相同的Foo。

foo.setBar(7);
int bar = foos[0].getBar(); // will get 7

The change to the object referenced by foo is observed inside the array. 在数组内部观察到foo引用的对象的更改。

foo = new Foo();
foo.setBar(94);
bar = foos[0].getBar(); // will not get 94

This change is not observed inside the array, as foo has been reassigned. 由于foo已被重新分配,因此在数组内部未观察到此更改。 Its setter is now mutating a different object entirely. 它的setter现在完全改变了另一个对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM