Let’s say I have a Node class. It has a single field, Node parentNode. It’s got setters and getters too.
I have 2 nodes: Node nodeA and Node nodeB.
Here’s what I want to do: set nodeB‘s parent to nodeA‘s parent, and then set nodeA‘s parent to 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())?
No,
nodeB.parentwill not be set tonull. Java always usesPass by Valueand notpass by reference. Repeat it 10 times.And in case you pass references, you pass them by value of references.
Let’s understand in more detail.
When you do: –
you simply create a copy of reference to
nodeA parent, and store it innodeB parent. So, you have now two references referring tonodeA parentobject.Now, when you setnodeA parenttonull, it is detached from thatparent, butnodeB parentreference is still there.