简体   繁体   English

如何遍历Java中的数组?

[英]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.

相关问题 如何遍历Java中的文本文件,将7行对象添加到对象数组中? - How do I loop through a text file in Java adding a 7 line object to an array of objects? Java程序。 如何在数组中循环“ isLucky”方法?如何在main方法中打印结果? - Java program. How do I loop my "isLucky method through the array? and how do I print the result in the main method? 如何在Java Eclipse数组的循环中修复此循环? - How do i fix this loop in a loop in a array, Java Eclipse? 如何循环通过 java.io 异常 (502)? - How do I loop through a java.io exception (502)? 如何在 Java 中循环按钮并禁用它们? - How do I loop through buttons and disable them in Java? 如何遍历每个数组项并除以二? - How do I loop through each array item and divide by two? 如何构造一个数组并使用循环将其初始化为值 1 到 5? - How do I construct an array and initialize it to the values 1 through 5 using a loop? java.lang.AssertionError。 如何正确地通过循环填充数组。 我不知道为什么我的代码不起作用 - java.lang.AssertionError. How correctly fill an array through the loop. I do not know why my code does not work 如何通过Java中的ArrayList创建和使用稀疏数组? - How do I create and use a sparse array through ArrayList in Java? Java:如何通过变量指向数组项? - Java: how do I point at an array item through a variable?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM