简体   繁体   中英

Build Map Using Recursive Function

The idea of the function is that it will build a map that contains a key (path) and the data corresponding to that path. This is why I keep passing the map back as it's being built.

The problem seems to be that it gets to the point where there are no children, yet still appends the next path onto the current path:

Input for the path will always start with "/". We get the children for this, which may be level_1A, level_1C, level_1B. Then I recurse on each of these to see if they have children.

Assume that level_1A has children level_2A, level_2B. Somehow, the algorithm gets caught up and is appending like so:

/level_1A/level_2B/level_2A

Whereas, it should be treating these seperately, like this:

/level_1A/level_2A
/level_1A/level_2B

Here's what the entire structure would look like:

/level_1A            data_1A
/level_1A/level_2A   data_2A
/level_1A/level_2B   data_2B

/level_1B            (empty)

/level_1C            (empty)

Here's the recursive method:

public Map<String, String> getAll(String path, Map<String, String> all) throws Exception {

        List<String> children = client.getChildren().forPath(path);

        if(children != null && children.size() > 0) {

            for(String child: children) {
                                                                                                    System.out.println("child: " + child);
                if(!path.equals("/")) { 
                    path = path + "/" +  child;
                } else {
                    path = path + child;
                }

                Stat stat = client.checkExists().watched().forPath(path);

                if(stat != null && stat.getDataLength() > 0) {
                    all.put(path, new String(client.getData().forPath(path)));
                }

                getAll(path, all);
            }

        } 

    return all;
}

The error is here:

 for(String child: children) {           
     if(!path.equals("/")) { 
         path = path + "/" +  child;
     } else {
         path = path + child;
     }
     ...
 }

path variable is out of for loop scope, so in the first iteration you've modified path variable and in the second iteration that modified value is been concatenated with second child and then been passed deeper.

So Just provide for-loop scoped variable and use it in iteration:

 for(String child: children) {
     String pathChild = path;           
     if(!path.equals("/")) { 
         pathChild = path + "/" +  child;
     } else {
         pathChild = path + child;
     }
     //pathChild is used below
     ...
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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