简体   繁体   English

递归Java程序中的新对象创建

[英]New Object Creation in recursive Java program

Java newbie here looking for some help. Java新手在这里寻求一些帮助。 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. 这样做是在递归循环的每次迭代中不断附加到SAME StringBuffer,当我真正希望能够做到这一点时,它每次都会创建一个全新的StringBuffer。 Any way to force a new StringBuffer to be created? 有什么方法可以强制创建一个新的StringBuffer?

Hopefully that made sense; 希望这是有道理的; let me know where I can clarify. 让我知道我可以澄清的地方。 Thank you! 谢谢! :) :)

You are creating a new StringBuffer each time through: 您每次创建一个新的StringBuffer:

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: 但是你要在下一行中附加传入的StringBuffer的内容,所以看起来你每次都使用相同的StringBuffer,但你不是:

newSB.append(buf);

Maybe that's not what you wanted? 也许这不是你想要的? Try stepping through this with a debugger. 尝试使用调试器逐步完成此操作。

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? 无论IF / ELSE采用哪条路径,您打算打印相同的东西,为什么要有条件部分呢?

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. 您确实在创建一个新的StringBuffer对象,本地作用于此函数。 However, you are appending the contents of the parameter, buf , to the new StringBuffer . 但是,您将参数buf的内容附加到新的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. 这可能会让您觉得您在函数的每次迭代中都附加到相同的StringBuffer ,但实际上您每次都在创建一个新的。

If you could clarify the problem a little more I think we could help. 如果你能更多地澄清问题,我想我们可以提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM