0

我试图将一个对象的引用从一个对象移动到另一个对象,从而在移动对象时删除对象的引用,并将引用添加到它被移动到的对象。

我会尽量用一些假课程来设置场景:Frog、Owner、Customer :D

所以我有一个拥有一系列青蛙的所有者,这些可以借给客户。一个客户只能引用一只青蛙。因此,当 Frog 被借出时,可以在 Customer 类中创建对该 Frog 的引用,并且可以从 Frogs 的所有者集合中删除 Frog。

我想知道的是我如何扭转这个动作。当我希望客户返回 Frog 时,我可以将引用 Frog 的 Customer 的实例变量设为 null,但是我不确定如何在不引用 Frog 的情况下将此 Frog 返回给所有者,例如:

public void returnFrog()
{
owner.returnFrog(frog);
frog = null;
}

一旦我使实例变量为空,已经返回给所有者的引用也将变为空。

我能想到的唯一方法是让客户拥有一个 Frog 的列表,然后简单地将 Frog 从列表中删除。这样引用永远不会设置为 null,但是有更好的方法吗?我坚信如果我只需要一个值,我就不应该使用 List 。:(

或者我无法四处移动对象,只跟踪 Frog 是否与客户相关联——如果是,则无法与任何其他客户相关联(这是我的解决方案 atm)。

希望我不会错过一些基本的东西。

4

2 回答 2

1

The code above works, your expectations are probably wrong: The method returnFrog() adds the reference frog (= the instance to which the variable frog points to) to the list of frogs in the owner instance.

Assigning a new value to the variable frog afterwards has no effect on the code executed inside returnFrog().

This becomes more clear when you think of frog as an alias for the instance:

Frog a = new Frog();
b = a; // doesn't copy the frog
b = null; // doesn't change a

This doesn't copy the frog; there is still just a single instance but at different times, you have different variables contain references that point to this instance. But changing the reference b doesn't affect a since assigning instances to references doesn't change the instances; it just changes the reference.

于 2013-10-29T12:23:45.460 回答
1

我认为您误解了变量和引用的工作方式。

这一行:

frog = null;

将值分配null给变量frog,我假设它是Customer类的实例变量。它不会影响任何其他变量!

所以,如果这一行:

owner.returnFrog(frog);

最终将对所讨论的两栖动物的引用存储到 中的变量中Owner,然后在将 null 分配给 中的变量后,该引用仍然存在User

一个物理隐喻是在纸上写下建筑物的地址。假设你有一张纸,上面有一个好的理发师的地址,而我有一张空白的纸。你告诉我地址​​,我写下来。现在你擦掉你的纸。我的纸会变成空白吗?

于 2013-10-29T12:25:05.937 回答