繁体   English   中英

基于表示层次结构的字符串列表的Java对象树

[英]Tree of java objects based on a list of strings representing hierarchy

我有一个有趣的事情,据我了解,这不是最简单的任务。

我需要基于表示层次结构的字符串列表创建对象树。

例如,列表中的字符串是(实际上可以是任何图形):

List<String> hierarchies;

1#1#2#1#2#3#1#2#4#1#2#4#5#

我的班级:

class Tree {

    List<Tree> children;

    // here is getter

}

我有一些实现,但仅用于开始。 我不知道如何完成这段代码。 你能和我分享你的愿景吗?

提前致谢!

Tree tree = null;

for (String hierarchy : hierarchies) {

    if (hierarchy.equals("1#")) {
        tree = new Tree();
    } else {
        tree.getChildren().add(new Tree());
    }

}

return tree;

有很多可能的解决方案。 没有复杂性,它看起来可能像:

public void testHierarchy() {

    List<String> hierarchies = new ArrayList<String>();

    hierarchies.add("1#");
    hierarchies.add("1#2#");
    hierarchies.add("1#2#3#");
    hierarchies.add("1#2#4#");
    hierarchies.add("1#2#4#5#");

    Tree root = new Tree();
    for (String hierarchy : hierarchies) {
        String[] elHierarchy = hierarchy.split("#");
        processLevel(elHierarchy, root);
    }
}

private void processLevel(String[] hierarchy, Tree rootTree) {

    if (null == rootTree.getValue() || "".equals(rootTree.getValue())) {
        rootTree.setValue(hierarchy[0]);
    }

    Tree nextChild = null;
    for (Tree child : rootTree.getChildren()) {
        if (child.getValue().equals(hierarchy[1])) {
            nextChild = child;
            break;
        }
    }

    if (hierarchy.length > 1) {
        if (null == nextChild) {
            nextChild = new Tree();
            nextChild.setValue(hierarchy[1]);
            rootTree.getChildren().add(nextChild);
        }
        String[] remainHierarchy = new String[hierarchy.length - 1];
        System.arraycopy(hierarchy, 1, remainHierarchy, 0,  remainHierarchy.length);
        processLevel(remainHierarchy, nextChild);
    }
}

private static class Tree {
    String  value;
    List<Tree>  children    = new ArrayList<SometestTest.Tree>();

    public List<Tree> getChildren() {

        return children;
    }

    public String getValue() {

        return value;
    }

    public void setValue(String value) {

        this.value = value;
    }

}

PS不太优雅,但简单。

暂无
暂无

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

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