的的toString有這樣的結構:如何將新行添加到多樹
public class TreeNode {
private String key;
private List<TreeNode> children;
....
}
我重寫ToString()函數
@Override
public String toString() {
String treeStructure = "TreeNode [key=" + key + "]";
if(children!=null){
for(TreeNode child:children){
treeStructure = treeStructure+"--- >"+children.toString()+"/n";
}
}
return treeStructure;
}
然後我測試結果:
public static void main(String[] args) {
TreeNode node = new TreeNode();
node.setKey("root");
List<TreeNode> children = new ArrayList<TreeNode>();
TreeNode child1 = new TreeNode();
child1.setKey("child1");
TreeNode child2 = new TreeNode();
child2.setKey("child2");
children.add(child1);
children.add(child2);
List<TreeNode> grandchildren = new ArrayList<TreeNode>();
TreeNode grandchild = new TreeNode();
grandchild.setKey("grandchild");
grandchildren.add(grandchild);
node.setChildren(children);
child1.setChildren(grandchildren);
System.out.println(node);
}
但是,當我運行它的輸出是:
TreeNode [key=root]--->[TreeNode [key=child1]--->[TreeNode [key=grandchild]]/n, TreeNode [key=child2]]/n--->[TreeNode [key=child1]--->[TreeNode [key=grandchild]]/n, TreeNode [key=child2]]/n
我怎樣才能在輸出中添加換行是這樣的:
TreeNode [key=root]--->TreeNode [key=child1]--->TreeNode [key=grandchild]
--->TreeNode [key=child2]
但現在的child1顯示出兩次,不加入新行結果。
================================ 我改變了功能:
@Override
public String toString() {
String treeStructure = "TreeNode [key=" + key + "]";
if(children!=null){
for(TreeNode child:children){
treeStructure = treeStructure+"\n"+"-->"+children.toString()+"\n";
}
}
return treeStructure;
}
然後輸出結果如下:
TreeNode [key=root]
--->[TreeNode [key=child1]
--->[TreeNode [key=grandchild]]
, TreeNode [key=child2]]
--->[TreeNode [key=child1]
--->[TreeNode [key=grandchild]]
, TreeNode [key=child2]]
爲什麼孩子重複兩次,「?」從哪裏來?
在Java中,換行符是「\ n」,而不是「/ n」。 –
看到[我的答案#打印](http://stackoverflow.com/questions/10497119/how-to-save-the-path-of-search-result-in-java-multi-tree/10499759#10499759) – BLUEPIXY