1

The code in Java:

private BiNode root = null;

//constructor
BST(int[] r) {
    BiNode s = new BiNode(r[0], null, null);
    test(root, s);
}

private  void test(BiNode head, BiNode s){
    head = s;

    if (head != null)
        System.out.println("head is not null");
    if (root == null)
        System.out.println("root is null");
}

Output:

head is not null
root is null

Why does root not equal head in the test method?

Jonny Henly
  • 4,023
  • 4
  • 26
  • 43
learner
  • 1,381
  • 1
  • 10
  • 16

1 Answers1

1

When you pass root in the constructor to the method test, the method actually uses a new pointer to the object's value, which is null (root's value). So in the method when you change the value of head to s you are not making any changes to root's pointer, which remains as null, but head´s value changes.

This is a java hindrance, which is you cannot pass pointers, and nothing you can do in java will get around this, so you have to set root directly.

Sakamiai
  • 385
  • 3
  • 13
  • I get your point. If I want to change 'root' in 'test', I should first initiate : 'root = new BiNode(); '. Is it right? – learner Apr 24 '16 at 10:24
  • No, even initiating it won't change a thing. You have to assign it directly, so you have to put 'root = something;'. You could make an object that has a `root` field, then pass that object to a method and change that object's field to whatever you want, but this would require some time to elaborate, and I don't see what's your goal here :) – Sakamiai Apr 24 '16 at 10:31