我有一个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中的项重复次数过多。它最初显示正确的层次结构,然后开始重复随机变化。
任何人都可以指出我正确的方向吗?
答案 0 :(得分:1)
static void displayContent(ArrayList<Materials> materials) {
ArrayList<Materials> childs = new ArrayList<Materials>();
for (Materials material : materials) {
childs = selectChild(material.id);
if(childs.isEmpty()) {
System.out.print(" - ");
}
System.out.println(material.content);
displayContent(childs);
}
}
在打印材料内容之前检查列表是否为空将添加 - 为最后一个元素。
对于系统标签,您将必须计算遍历(例如,孩子的孩子的孩子是3)并添加许多标签。 This answer可以帮助解决这个问题。感谢Dukeling指出它。
答案 1 :(得分:1)
问题是,在您第一次打电话给displayContent
时,您将传递整个材料列表。所以它会这样做:
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);