Java-创建对同一对象的两个引用 [英] Java - Creating Two References to the Same Object

查看:71
本文介绍了Java-创建对同一对象的两个引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查以下代码:

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

有什么方法可以使两个数组都指向同一个对象,以便当我在一个数组中更改 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?

感谢您的帮助!

结果,我上面的代码确实做到了.问题出在我代码的其他地方.我为我的困惑感到歉意...

Turns, out my above code does exactly that. Problem was elsewhere in my code. My apologies for my confusion...

推荐答案

取决于更改"的含义.如果您要像调用setter和对对象进行突变那样指更改,那么将观察到这些更改.如果您将更改视为完全重新分配或覆盖变量(或引用),则不会观察到这些更改.

Depends what you mean by "change." If you mean change as in calling setters and mutating the object, then those changes are observed. 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;

数组中的项目和变量均引用相同的Foo.

The item in the array and the variable each reference the same Foo.

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

在数组内部观察到对foo引用的对象的更改.

The change to the object referenced by foo is observed inside the array.

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

由于重新分配了foo,因此在数组内部未观察到此更改.现在,它的设置器正在完全变异另一个对象.

This change is not observed inside the array, as foo has been reassigned. Its setter is now mutating a different object entirely.

这篇关于Java-创建对同一对象的两个引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆