Related to my question about how to build a tree-like structure , the data I receive from the server are in arrays like this: {School Chair Table Chalk}
How can I loop through this so that:
School
becomes parent of Chair
Chair
becomes parent of Table
Table
becomes parent of Chalk
Assuming a Node class that offers a constructor which accepts the node's value as an argument and method addChild that adds another Node as a child and sets itself as the child's parent, the code could look like this:
Node currentNode = null;
for(String value: array) {
Node node = new Node(value);
if(currentNode != null) {
currentNode.addChild(node);
}
currentNode = node;
}
Are they always in a list that becomes hierarchical in order? I would suggest creating a simple wrapper class...pardon my syntax, as I've been playing in C# for a while now:
public class Node {
public string description;
public Node child;
public Node(List<string> descriptions) {
this.description = descriptions.RemoveAt(0);
if (descriptions.Count > 0) {
this.child = new Node(descriptions); //create child node with remaining items
}
}
}
This will take issue if you pass in a list w/ zero items to the constructor, but that's easily remedied.
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.