Reputation: 41909
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())
?
Upvotes: 1
Views: 81
Reputation: 213193
nodeA.setParent(null); // bad since nodeB.getParent() will = null
No, nodeB.parent
will not be set to null
. Java always uses Pass by Value
and not pass 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: -
nodeB.setParent(nodeA.getParent());
you simply create a copy of reference to nodeA parent
, and store it in 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.
Upvotes: 2
Reputation: 26574
Because nodeX.parent is a reference to an object:
nodeB.setParent(nodeA.getParent())
you are saying to nodeB "here is the address of nodeA's parent."nodeA.setParent(null);
you are saying to nodeA "Forget where your parent lives. Your parent is now nothing."Upvotes: 3