Reputation: 51
I have two references, reference a point to object a, reference b point to object b, then I called a swap function to try to let a point to object b, b point to object a, it is swapped in the swap function, but result in main function didn't change. So what I should do?
The swap function:
private void swap(Stack<TreeNode> a, Stack<TreeNode> b) {
Stack<TreeNode> temp = new Stack<TreeNode>();
temp = a;
a = b;
b = temp;
}
Upvotes: 1
Views: 92
Reputation: 3190
You're changing local parameters, not the acutal contents of those references. One solution is to modify the instances you're sending. E.g.
private boolean swap(Stack<TreeNode> a, Stack<TreeNode> b)
{
if(a == null || b == null) return false;
Stack<TreeNode> temp = new Stack<>();
while(!a.empty()) temp.add(a.pop());
while(!b.empty()) a.add(0, b.pop());
while(!temp.empty()) b.add(temp.pop());
return true;
}
Upvotes: 2
Reputation: 236004
The result of the swap is local to the method, it won't have any effect once the method returns to its calling point - you're simply swapping local variables. When the method got invoked, a copy of a reference to the objects got passed, not the actual objects themselves.
Java has pass-by-value semantics, in the case of objects being passed as parameters to a method that means that a copy of the reference is passed. Take a look at this post for an example.
Also notice that the object references existing before calling the method, and the references existing inside the method as parameters are actually pointing to the same object, so any modifications to the object's contents you do inside a method will remain in place once the method returns.
Upvotes: 5