Gregory-Turtle
Gregory-Turtle

Reputation: 1717

Inserting into a tree in Java

In a Java file, I have the following code:

MyTree atree = new MyTree();
atree.insert(1);

This is not a regular tree. "atree" is the root node. Every node in this tree has 5 children, all initially set to null. The parameter for insert is the child that you want to 'activate', that is, make it non-null. So I have a method in the MyTree class that does this:

public void insert(int i)
{
    if(i == 1)
    {
        MyTree current = this.getChildOne();
        current = new MyTree();
    }
}

After I call the function, I check the first node in the file where I called it.

if(atree.getChildOne() == null)
{
    return -1;
}

And it always returns negative one. I suspect that the insert function is actually working on a copy of 'atree' and not the actual 'atree'. But I am not entirely sure. Anyone have an explanation?

Upvotes: 0

Views: 208

Answers (2)

Jeff Storey
Jeff Storey

Reputation: 57212

It doesn't look like you are assigning child one anywhere. The code

MyTree current = this.getChildOne();
current = new MyTree();

does not assign child one. You initialize a local variable current but then that variable is lost when the method ends.

I think you probably want to do something like this in your insert method

if ( i == i ) {
   this.childOne = // assign it here
}

Upvotes: 3

ruakh
ruakh

Reputation: 183602

The line current = new MyTree() changes the local variable current: it had pointed to the instance that this.getChildOne() points to, now it points to a new instance. (So you might as well eliminate the assignment current = this.getChildOne(): unless getChildOne has side effects, this assignment is pointless, because you immediately overwrite it by setting current to something else.)

To actually modify some attribute of this, you'll want to write something like:

if(i == 1)
{
    this.setChildOne(new MyTree());
}

Upvotes: 0

Related Questions