简体   繁体   English

Java对对象的引用

[英]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 nodeANode 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。

  1. nodeB.setParent(nodeA.getParent());
  2. 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是对对象的引用,所以:

  • When you call nodeB.setParent(nodeA.getParent()) you are saying to nodeB "here is the address of nodeA's parent." 当您调用nodeB.setParent(nodeA.getParent())您对nodeB说:“这是nodeA的父级地址。”
  • When you then say nodeA.setParent(null); 然后说出nodeA.setParent(null); you are saying to nodeA "Forget where your parent lives. Your parent is now nothing." 您对nodeA说:“忘记父母的住处。您的父母现在一无所有。”
  • You said nothing to nodeB in the second statement, which still has the address to what is now its parent. 您没有在第二个语句中对nodeB说什么,该语句仍具有到其当前父节点的地址。

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.

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