views:

229

answers:

2

Hi there, Java newbie here looking for some help. Here is the code in question:

public void generateCodeTable(Node tree, StringBuffer buf) {
        if (tree != null) {
            StringBuffer newSB = new StringBuffer();
            newSB.append(buf);
            if (tree.key != '$') {
                System.out.print(tree.key + "(" + buf + ") " );
            } else {
                System.out.print(tree.key + "(" + buf + ") " );
            }
            generateCodeTable(tree.getLeftNode(), newSB.append(1));
            generateCodeTable(tree.getRightNode(), newSB.append(0)); 
        }

What this does is continually append to the SAME StringBuffer in every iteration of the recursive loop, when really what I'd like to be able to do it have it create a brand-new StringBuffer every time through. Any way to force a new StringBuffer to be created?

Hopefully that made sense; let me know where I can clarify. Thank you! :)

+2  A: 

You are creating a new StringBuffer each time through:

StringBuffer newSB = new StringBuffer();

But you're appending the contents of the passed in StringBuffer in the next line, so it looks like you're using the same StringBuffer every time, but you're not:

newSB.append(buf);

Maybe that's not what you wanted? Try stepping through this with a debugger.

Ken Liu
+1  A: 

Could you better explain what you are trying to do?

I find this code section to be particularly confusing.

        if (tree.key != '$') {
            System.out.print(tree.key + "(" + buf + ") " );
        } else {
            System.out.print(tree.key + "(" + buf + ") " );
        }

You are going to print the same thing, regardless of which path the IF/ELSE takes, so why have the conditional part?

Also, when you do the following:

StringBuffer newSB = new StringBuffer();
newSB.append(buf);

You really are creating a new StringBuffer object, scoped locally to this function. However, you are appending the contents of the parameter, buf, to the new StringBuffer. This may give the illusion that you are appending to the same StringBuffer in every iteration of the function, but you are really creating a new one every time.

If you could clarify the problem a little more I think we could help.

Brad Barker