Jump to content
  • Advertisement
Sign in to follow this  
fpsgamer

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

This topic is 4452 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!