Reputation:
In a binary search tree that takes a simple object.....when creating the getter and setter methods for the left, right, and parent. There are concerns about what is happening when a parent node is set. Code bellow...
The code:
public void setParent(Person parent) {
parent = new Person( parent.getName(), parent.getWeight());
The example code that inspired the code:
public void setParent(Node parent) {
this.parent = parent;
}
Upvotes: 0
Views: 179
Reputation:
You're creating what is essentially a clone of the parent object. This is different from just saving the pointer to the parent object.
Obviously, you'll be taking more memory space by duplicating the parent object. More importantly, you're not duplicating the parent's references. So if you try to traverse the tree, go to a node's parent, then try to visit its other children, you draw a bunch of null pointers.
The this.parent
is a reference to the current object's parent
pointer.
It doesn't actually mean that this
is a parent. In fact, this.parent
is used to distinguish the local parent
pointer from the incoming parameter parent
.
class Person{
Person parent; // <---- this is the "this.parent" attribute, and is initially undefined
public void setParent(Person parent){ // <---- the "Person parent" on this line is an incoming parameter
this.parent = parent; //<---- "this.parent" refers to the attribute, and "parent" refers to the parameter
}
}
Upvotes: 1