[英]How do I loop through a text file in Java adding a 7 line object to an array of objects?
[英]How do I loop through an array in Java?
與我有關如何構建樹狀結構的問題有關,我從服務器接收的數據位於以下數組中: {School Chair Table Chalk}
我如何遍歷此,以便:
School
成為Chair
家長 Chair
成為Table
父母 Table
成為Chalk
父對象 假設Node類提供了一個接受該節點值作為參數的構造函數,並使用addChild方法將另一個Node作為子級添加,並將其自身設置為該子級的父級,則代碼如下所示:
Node currentNode = null;
for(String value: array) {
Node node = new Node(value);
if(currentNode != null) {
currentNode.addChild(node);
}
currentNode = node;
}
它們是否始終在按順序成為層次結構的列表中? 我建議創建一個簡單的包裝類...請原諒我的語法,因為我已經在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
}
}
}
如果將帶有零項的列表傳遞給構造函數,則會出現問題,但這很容易解決。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.