-1

I am trying to insert a node into my tree using Node as a nested class. I can't figure out why the tree.root won't save the node using my method insertNode

public class Tree {
  Node root;

  private class Node {
    int value;
    Node(int value) {
      this.value = value;
    }
  }

  public static void main(String[] args) {
    Tree tree = new Tree();
    tree.insertNode(4, tree.root);
    System.out.println(tree.root);

  }

  public void insertNode(int value, Node n){
    if(n == null ){
      n = new Node(value);
    }
  }   

}

>> null

What am I missing? Thank you for your help

tore
  • 303
  • 3
  • 11
  • Which parts of your code you don't understand what they do? – nbro Dec 25 '17 at 20:42
  • @nbro I think the problem is that when I use insertNode, the Node that I save to tree.root, is not saved outside the method. Outside its scope? I don't understand why that is – tore Dec 25 '17 at 20:45
  • "the Node that I save to tree.root", where are you saving it? Hint: nowhere. `n` is a reference to an object, not a field of the object you want to add a node to. Do some research on the difference between references and objects and between variables, arguments, fields, etc, in Java. – nbro Dec 25 '17 at 20:56
  • @Siguza That link helped! Thank you – tore Dec 25 '17 at 21:16

1 Answers1

2

What your code does is the following:

  1. It creates a new Tree. The root Node will be initialized by the compiler to the default value null.
  2. You are "inserting" something into the Tree at least this is what the method name suggests. In fact, the method does nothing except to set an argument to a default value if it is null.
  3. You are printing out the root Node of your Tree which is null.

I think you should change your insertNode method so it actually modifies the state of your Tree.

Edit: As I read the comments below your question I noticed something that I missed at first. In your insertNode method you probably intended to do exactly what I described above. But what you do is something different: You assign something to a local variable instead of a member variable. Written in an explicit notation you want to do this instead:

this.root = new Node(value)

The difference is that in your code n is not bound to the object but Tree.root is meaning that changes (more precisely, assignments) to n will not be persistent and will void when the method returns. If you assign an object to Tree.root then this change will be reflected in the Tree object.

etaloof
  • 642
  • 9
  • 21
  • I'm not sure what to do now. After reading about 'Is Java “pass-by-reference” ', and you answer, I think the answer is to say 'tree.insertNode(5); void insertNode(int v){this.root = new Node(v);}` But the next step, building a binary tree, confuses me. Should I edit this question? Or start a new one? – tore Dec 25 '17 at 21:12
  • You did answer my question :) So I accepted your answer. Thank you! – tore Dec 25 '17 at 21:14