[英]Java Reference to Objects
Let's say I have a Node
class. 假设我有一个
Node
类。 It has a single field, Node parentNode.
它具有单个字段
Node parentNode.
It's got setters and getters too. 它也有设置者和获取者。
I have 2 nodes: Node nodeA
and Node nodeB
. 我有2个节点:
Node nodeA
和Node nodeB
Node nodeA
。
Here's what I want to do: set nodeB
's parent to nodeA
's parent, and then set nodeA
's parent to null. 这是我想做的事:设定
nodeB
的父nodeA
的父母,然后设置nodeA
的父为null。
nodeB.setParent(nodeA.getParent());
nodeA.setParent(null);
// bad since nodeB.getParent() will = null
To achieve the above, must I clone nodeA,
and then do nodeB.setParent(nodeAClone.getParent())
? 为了实现上述目的,我必须克隆
nodeA,
然后再进行nodeB.setParent(nodeAClone.getParent())
吗?
Because nodeX.parent is a reference to an object: 因为nodeX.parent是对对象的引用,所以:
nodeB.setParent(nodeA.getParent())
you are saying to nodeB "here is the address of nodeA's parent." nodeB.setParent(nodeA.getParent())
您对nodeB说:“这是nodeA的父级地址。” nodeA.setParent(null);
nodeA.setParent(null);
you are saying to nodeA "Forget where your parent lives. Your parent is now nothing." nodeA.setParent(null);
nodeA.setParent(null); // bad since nodeB.getParent() will = null
//不好,因为nodeB.getParent()将= null
No, nodeB.parent
will not be set to null
. 不会,
nodeB.parent
不会设置为null
。 Java always uses Pass by Value
and not pass by reference
. Java始终使用“
Pass by Value
pass by reference
而不是“ pass by reference
。 Repeat it 10 times. 重复10次。
And in case you pass references, you pass them by value of references. 如果传递引用,则按引用值传递它们。
Let's understand in more detail. 让我们更详细地了解。
When you do: - 当您这样做时:-
nodeB.setParent(nodeA.getParent());
you simply create a copy of reference to nodeA parent
, and store it in nodeB parent
. 您只需创建的参考副本
nodeA parent
,并将其存储在nodeB parent
。 So, you have now two references referring to nodeA parent
object.Now, when you set nodeA parent
to null
, it is detached from that parent
, but nodeB parent
reference is still there. 因此,现在有两个引用
nodeA parent
对象的引用。现在,当将nodeA parent
设置为null
,它将与该parent
对象分离,但nodeA parent
nodeB parent
引用仍然存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.