Skip to main content
gamedev.net
🔒 Locked

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

Started by fpsgamer Oct 4, 2006 at 7:47 PM 3 replies 1.1k views
Original Post
fpsgamer
fpsgamer
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
Si Hao
Si Hao
I don't think you can use return in a void method.
bgilb
bgilb
its not the same kind of return
shmoove
shmoove
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
King of Men
King of Men
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.
To win one hundred victories in one hundred battles is not the acme of skill. To subdue the enemy without fighting is the acme of skill.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.