0

Pass by value and by reference - I do this all the time in C++. But I'm wondering the behavior of java.

I'm writing a BST and conjured the following method:

private Node<T> get_node(T data)
{
    Node<T> tmp = null;
    if (isEmpty())
    {
        return null;
    }
    tmp = root;
    while (tmp != null)
    {
        //System.out.println("tmp is " + tmp.getData());
        if (compare(tmp.getData(), data) < 0) //data is greater
        {
            System.out.println("get right");
            tmp = tmp.getRight();
        }
        else if (compare(tmp.getData(), data) < 0) //tmp is greater
        {
            System.out.println("get left");
            tmp = tmp.getLeft();
        }
        else if (compare(tmp.getData(), data) == 0) //we found it
        {
            System.out.println("get left");
            return tmp;
        }
    }
    return null;
} 

This is in the BST class itself - I am using this helper function to construct a new BST in "this".

The problem is, I don't think this method is actually returning the ACTUAL Node in this. I think it is returning a copy or something likewise useless to me. I really want this to return the ACTUAL Node in this.

How is this done? Is this done at all?

PinkElephantsOnParade
  • 6,452
  • 12
  • 53
  • 91

1 Answers1

1

Java do not do pass by reference it is always pass by value.

For object, Object reference are also pass as a copy, so if you have a copy of the reference you will be able to manipulate value, but do not get confuse this with pass by reference.

public void swap(Point a, Point b)
{
  Point temp = a;
  a = b;
  b = temp;
}
Point x;
Point y;

swap(x, y);

after the execution of the swap x and y still have same reference.

But following code will change the value

public void change(Point a)
    {
      a.x=10; //reference is copied but same, so value will change 
    }
Point x;
change(x);
minhaz
  • 4,233
  • 3
  • 33
  • 49