我写了一个n-ary树ADT工作正常.但是,我需要将其序列化存储在变量调用类中.例如.
DomTree<String> a = Data.createTreeInstance("very_large_file.xml"); String x = a.toString();
我编写的方法完全符合我的需要,但是在非常大的输入上它需要永远(在100MB xml文件上20分钟) – 我有时间方法并从xml文件构建树很快,但调用toString()如上所示非常慢.
@Override public String toString(){ return printTree(this); } public String printTree(AbstractTree<E> tree){ if (tree.isLeaf()){ return tree.getNodeName(); }else{ String tStr = tree.getNodeName() + "("; int i = 0; Iterator<AbstractTree<E>> child = tree.getChildren().iterator(); while (i < tree.getChildren().size() - 1){ tStr += printTree(child.next()) + ","; i++; } tStr += printTree(child.next()) + ")"; return tStr; } }
我猜它是用字符串构建的方式而不是遍历树的方式?有一个更好的方法吗?
更新:遵循Skaffman的示例,以下代码为非常大的输入提供outOfMemoryError.
@Override public String toString(){ StringBuilder buffer = new StringBuilder(); printTree(this,buffer); return buffer.toString();
}
public String printTree(AbstractTree<E> tree,StringBuilder buffer){ if (tree.isLeaf()){ return tree.getNodeName(); }else{ buffer.append(tree.getNodeName()); buffer.append("("); int i = 0; Iterator<AbstractTree<E>> child = tree.getChildren().iterator(); while (i < tree.getChildren().size() - 1){ buffer.append(printTree(child.next(),buffer)); buffer.append(","); i++; } buffer.append(printTree(child.next(),buffer)); buffer.append(")"); return buffer.toString(); } }
更新:现在使用Skaffmans示例完美地工作
解决方法
像这样的字符串连接速度非常慢.使用StringBuilder.
@Override public String toString(){ StringBuilder buffer = new StringBuilder(); printTree(this,buffer); return buffer.toString(); } public void printTree(AbstractTree<E> tree,StringBuilder buffer){ if (tree.isLeaf()){ buffer.append(tree.getNodeName()); } else { buffer.append(tree.getNodeName()); buffer.append("("); int i = 0; Iterator<AbstractTree<E>> child = tree.getChildren().iterator(); while (i < tree.getChildren().size() - 1){ printTree(child.next(),buffer); buffer.append(","); i++; } printTree(child.next(),buffer); buffer.append(")"); } }