1

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;
}
MariuszS
  • 30,646
  • 12
  • 114
  • 155

2 Answers2

5

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.

Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • @paulsm4 hmmm, yes. If you pass, say, an empty list, and add elements to it inside a method, after the method returns the list _will_ contain those objects. – Óscar López Nov 23 '13 at 20:18
2

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;   
}
blackcompe
  • 3,180
  • 16
  • 27