[英]How do I loop through an array in Java?
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}
与我有关如何构建树状结构的问题有关,我从服务器接收的数据位于以下数组中:
{School Chair Table Chalk}
How can I loop through this so that: 我如何遍历此,以便:
School
becomes parent of Chair
School
成为Chair
家长 Chair
becomes parent of Table
Chair
成为Table
父母 Table
becomes parent of Chalk
Table
成为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类提供了一个接受该节点值作为参数的构造函数,并使用addChild方法将另一个Node作为子级添加,并将其自身设置为该子级的父级,则代码如下所示:
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:
我建议创建一个简单的包装类...请原谅我的语法,因为我已经在C#中玩了一段时间了:
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. 如果将带有零项的列表传递给构造函数,则会出现问题,但这很容易解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.