【问题标题】:String path to a tree data structure (GWT)树数据结构 (GWT) 的字符串路径
【发布时间】:2011-11-22 21:52:09
【问题描述】:

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

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

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

【问题讨论】:

标签: java gwt data-structures tree


【解决方案1】:
    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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多