Sign in to follow this  
fpsgamer

[java] Recursive Functions and Passing parameters by Reference....

Recommended Posts

It has been a while since I have programmed in Java and I am having a hard time with the ways variables are passed. So as I understand it all variables passed into functions are passed into functions by reference, though the reference itself is passed by value. So how on earth would I do this:

class BST{
private Node root;

    /** Insert node x into the dictionary */
    public void insert(Node z) {
    	insert(z, root);
    }
    
    private void insert(Node z, Node node){
    	if(node == null){
    		// error!!!!!
                node = z;
    		return; // retun and unwind the stack
    	}
    	
     	if(z.value < node.value)
             insert(z, node.leftChild);
	else
	     insert(z, node.rightChild);
}





The problem exists below the comment I that reads "error". Basically I want the value pointed to by node to change to the object pointed to by z. But since the references are local to the function nothing changes. What design practices does one follow in Java to get something like this to work? -thanks

Share this post


Link to post
Share on other sites
Instead of inserting Nodes you could try inserting the data saved in every Node and create the actual Nodes internally in the BST class. Something like:

class Node
{
void setData(NodeData data) {
this.data = data;
this.leftChild = new Node();
this.rightChild = new Node();
}
NodeData data;
Node leftChild;
Node rightChild;
}
class BST
{
private Node root = new Node();

public void insert(NodeData z) {
insert(z, root);
}

private void insert(NodeData z, Node node) {
if (node.data == null) {
node.setData(z);
return;
}
if (z.value < node.data.value) {
insert(z, node.leftChild);
} else {
insert(z, node.rightChild);
}
}
}


shmoove

Share this post


Link to post
Share on other sites
It is, alas, a bit of an ugly hack, but you can simulate pass-by-reference by wrapping your Node in an array. That is, each argument should be a Node[1]. That way you can change what the first element of the array points to, and it'll have non-local effect.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this