为什么下一个方法不打印任何内容,但是当我将 String 更改为 array 时,它可以正常工作?
不工作:
public String toString(){
//In-Order - left,root,right.
String s ="";
toString(root,s);
return s;
}
public void toString(BSTNode root,String s){
if (root!=null){
toString(root.left,s);
s=s+","+ root.data;
toString(root.right,s);
}
}
工作:
public String toString(){
//In-Order - left,root,right.
String[] s =new String[1];
s[0]="";
toString(root,s);
return s[0];
}
public void toString(BSTNode root,String[] s){
if (root!=null){
toString(root.left,s);
s[0]=s[0]+","+ root.data;
toString(root.right,s);
}
最佳答案
当您创建 String 数组并传递时,基本上它是在创建 String 对象(就像我们使用 new 运算符
创建的那样)。因此,它会请求相同的引用并在您处理字符串时修改该字符串。但在前一种情况下,它将它们视为两个单独的变量,就像 java 中处理基本类型一样。
public class StringTest {
public static void main(String[] args) {
String s[] = new String[1];
System.out.println("before: "+s[0]);
updateString(s);
System.out.println("after: " + s[0]);
}
private static void updateString(String s[]) {
s[0] = "New String";
}
}
程序的输出是:
before: null
after: New String
否则,它不会打印任何内容。
关于java - BST(二叉搜索树)中的字符串 toString 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32224112/