树数据结构的字符串路径(GWT)

时间:2011-11-22 21:52:09

标签: java gwt data-structures tree

我的挑战是......我得到一个字符串路径(例如x1 / x2 / x3 / Xn,Xn / x2 / x3等)(例如String path = Project.getName())。所以基本上,我可以有任何类型的路径(任何级别和任何深度)。我试图找到一种方法将其转换为数据结构,以便我可以在我的gwt CellTree中实现它。到目前为止,我已经从此示例GWT Cell tree, how to use?实现了CellTree。

因为,我不知道级别或深度,我有点迷失...我想我应该使用递归函数分割我的字符串路径然后添加它们,但检查它们是否已存在,等等...

我也查看了这个问题Construct a tree structure from list of string paths。但我对java和设计模式有点新意,所以任何指针或代码(例子)都会有所帮助。

1 个答案:

答案 0 :(得分:0)

    String fullPath = mystringpath;
    String[] paths = fullPath.split("/");
    String combinedPaths = "";
    Node current = this.root;

    // We will never process the last node since it could be a repository
    // or a wildcard. The last step of this process would be doing that.
    for (int i = 0; i < paths.length - 1; i++) {
        combinedPaths += "/" + paths[i];
        if (this.collected.containsKey(combinedPaths)) {
            current = this.collected.get(combinedPaths);
        }
        else {
            String name = paths[i];
            Node childItem = new Node(name);
            current.addItem(childItem);
            current = childItem;
            this.collected.put(combinedPaths, current);
        }
    }

    // Process the last node since it represents the repository name.
        String name = paths[paths.length - 1];
        Node leafItem = new Node(name);
        combinedPaths += "/" + name;
        current.addItem(leafItem);
        current = leafItem;
        this.collected.put(combinedPaths, current);