Reputation: 353
I was doing inorder traversals when in the solution I came across the following lines:
stack.push(current);
current = current.left;
Now my question is that when I push current into the stack and make current = current.left;
then will the node that is there within the stack
also change to current.left
? In my case, the current in the stack
still points to the original current
but the current
variable does point to current.left
. Why is this?
Upvotes: 1
Views: 66
Reputation: 3453
Java is pass-by-value. You pass the value of reference to object. Changing the reference will not affect copied reference value in stack
.
Upvotes: 0
Reputation:
You're changing what the variable "current" references, but the object in the Stack won't be changed just because your variable is now referencing a different object.
/* Misread the question ignore this...
If you're asking if the changes you make to the object 'current' will also have the same effect as the current object pushed to the stack. The short answer is yes.
You're pushing the object, not a clone. The object never changes or is cloned, and putting something in a Stack is just another way including your variable declaration to reference the object in memory.
The same applies to HashMap, ArrayList, etc. */
Upvotes: 1
Reputation: 2167
just look at it from other perspective:
in C/C++ you have pointers. All variables in java should be threated like those pointers. When you are calling a method, in fact you pass the new pointer to given object, rather than reference to it.
With =
you are just overriding value of pointer with pointer to new object, and old object still exists till garbage collector will collect it.
Upvotes: 0
Reputation: 65811
At a guess - because stack.push(current)
is taking a copy of current
for the stack.
Upvotes: 0