gpt4 book ai didi

java - 如何在Java中以树形结构显示列表数据?

转载 作者:行者123 更新时间:2023-12-02 02:10:39 25 4
gpt4 key购买 nike

我有一个 arrayList,我想以分层结构显示。

我希望结果看起来像这样。如果它没有任何子节点,我希望该项目用连字符缩进:

User Design
Lectures
Week 1
-Apr 5
-Apr 8
Week 2
-Apr 12
Activities
Personas
Male
-George
Female
-Allison
-Jessica

我尝试使用递归方法显示列表,但没有得到所需的结果。这是我到目前为止所尝试过的:

import java.util.*;

class Materials {
public int id;
public String content;
public int pid;

public Materials(int id, String content, int pid) {
this.id = id;
this.content = content;
this.pid = pid;
}
}
public class nestedList {

public static ArrayList<Materials> material;

public static void main(String[] args) {
material = new ArrayList<Materials>();
material.add(new Materials(1,"User Design", 0));
material.add(new Materials(2,"Lectures", 1));
material.add(new Materials(3,"Activities", 1));
material.add(new Materials(4,"Week 1", 2));
material.add(new Materials(5,"Apr 5", 4));
material.add(new Materials(6,"Apr 8", 4));
material.add(new Materials(7,"Week 2", 2));
material.add(new Materials(8,"Apr 12", 7));
material.add(new Materials(9,"Personas", 3));
material.add(new Materials(10,"Male", 9));
material.add(new Materials(11,"Female", 9));
material.add(new Materials(12,"George", 10));
material.add(new Materials(13,"Allison", 11));
material.add(new Materials(14,"Jessica", 11));

displayContent(material);

}

static void displayContent(ArrayList<Materials> materials) {
ArrayList<Materials> childs = new ArrayList<Materials>();
for (Materials material : materials) {
childs = selectChild(material.id);
System.out.println(material.content);
displayContent(childs);
}

}

static ArrayList<Materials> selectChild(int id) {
ArrayList<Materials> list = new ArrayList<Materials>();

for (int i = 0; i < material.size(); i++) {
if(material.get(i).pid == id) {
list.add(material.get(i));
}
}

return list;
}
}

当我运行此代码时,arrayList 中的项目重复太多次。它最初显示正确的层次结构,然后开始以随机变化重复。

谁能给我指出正确的方向吗?

最佳答案

问题在于,在第一次调用 displayContent 时,您传递了整个 Material 列表。所以它将执行以下操作:

Display the entire hierarchy for "User Design"
Display the entire hierarchy for "Lectures"
Display the entire hierarchy for "Activities"
etc.

您真正想要做的是在初始调用中仅将根元素传递给 displayContent。所以在你的主要内容中:

ArrayList<Materials> topLevel = selectChild(0);
displayContent(topLevel);

关于java - 如何在Java中以树形结构显示列表数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50095791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com