Reputation: 3931
I have the following java class, that has an instance variable property as a generic type passed when declaring the class.
When I try to assign the property passing it as a method argument, it does not seem to change its value if I change the value of the argument itself.
Code:
public class BST<T extends Comparable<T>, S>{
private Node<T, S> bstRoot;
public Node<T,S> getRoot() {
return bstRoot;
}
public void setRoot(Node<T,S> root) {
this.bstRoot = root;
}
public boolean put(T key, S value){
Node<T,S> node = new Node<T,S>(key, value);
return put(node, bstRoot);
}
private boolean put(Node<T,S> node, Node<T,S> root){
if(root == null){
root = node;
}
else{
if(root.compareTo(node) < 0){
put(node, root.getRightChild());
}
else{
put(node, root.getLeftChild());
}
}
return true;
}
}
When I do the following:
public class BSTTest {
public static void main(String[] args){
BST<Integer, String> bst = new BST<Integer, String>();
bst.put(10, "Hello10");
}
}
After doing the put, the bstRoot is still null, instead of being set to a value of Node object with key 10 and value Hello10. Is it not passing by reference then?
Upvotes: 0
Views: 572
Reputation: 1
private boolean put(Node<T,S> node, Node<T,S> root){
if(root == null){
root = node;
}
else{
if(root.compareTo(node) < 0){
put(node, root.getRightChild());
}
else{
put(node, root.getLeftChild());
}
}
return true;
}
Here root has a local scope. You have to set this root to bstRoot. since bstRoot is instance variable.
Upvotes: 0
Reputation: 206786
The problem is the following. In your first put
method, you do this:
return put(node, bstRoot);
Your second put
method looks like this:
private boolean put(Node<T,S> node, Node<T,S> root){
if(root == null){
root = node;
}
So, in the first put
method you pass bstRoot
as the root
argument for the second put
method.
You seem to expect that bstRoot
is passed by reference, so that the second put
method will set bstRoot
.
This is not the case. In Java, everything is passed by value. So, root
in your second method is a copy of bstRoot
, and modifying the value of root
will not modify bstRoot
.
Upvotes: 5
Reputation: 106389
This doesn't look quite right:
if(root == null){
root = node;
}
Why? root
is a variable defined in your method. It doesn't have the same lifecycle as a field in your instance.
private boolean put(Node<T,S> node, Node<T,S> root)
It would be more reliable to actually use bstRoot
for an empty tree here.
if(bstRoot == null){
bstRoot = node;
}
Upvotes: 2