Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Creating a Trie

807580May 2 2010 — edited May 3 2010
Hi guys, I'm trying to create my own Trie data structure, but it isn't going so smoothly. I've looked around, and I'm confused, some people say everything is passed by value, and others say objects are passed by reference in java.

Anyways I want to figure out why this won't work.
I pass a word to insertWord. Then I make a reference temp to the root of the trie. Then I use the insertLetter method to insert the letters one by one.

So what exactly is going on when I pass the Node reference temp to the insertLetter method? And what is being returned? A reference or an object?
I've tested this, and root never seems to change, it always remains null.

Is there anyway to fix this?
public void insertWord(String word)
    {
        Node temp = root;
        for(int i = 0; i < word.length()-1; i++)
        {
           temp = insertLetter(word.charAt(i), temp, false);
           temp = temp.child;
        }
        temp = insertLetter(word.charAt(word.length()-1),temp,true);
    }

    private Node insertLetter(char lt, Node node, boolean end)
    {
       if(node == null)
       {
           Node newNode = new Node(lt, end);
           node = newNode;
           return node;
       }
       else if (node.letter == lt)
       {
           return node;
       }
       else
       {
           return insertLetter(lt,node.sibling,end);
       }
    }
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 31 2010
Added on May 2 2010
1 comment
227 views