I'm new to Java and I'm making a multi-level console menu. I have an Item class, which has an ArrayList that could contain another Items with own ArrayLists of Items and so on.
public Item(String key, String name, ArrayList<Item> itemList) {
this.key = key;
this.name = name;
this.itemList = itemList;
}
I need to do info() (or any other method) of each Itemin all arrays (no matter how many nested arrays with Item objects we could have). I wrote some bad and not universal code executing method only of 3-level menu...
public void show() {
for (int i = 0; i != list.size(); i++) {
System.out.println(list.get(i).info());
if (!list.get(i).getItemList().isEmpty()) {
for (int j = 0; j < list.get(i).getItemList().size(); j++) {
System.out.println(list.get(i).getItemList().get(j).info());
if (!list.get(i).getItemList().get(j).getItemList().isEmpty()) {
for (int y = 0; y < list.get(i).getItemList().get(j).getItemList().size(); y++) {
System.out.println(list.get(i).getItemList().get(j).getItemList().get(y).info());
}
}
}
}
}
}
The result of it look like:
1. Section one.
1.1. Sub-Section one.
1.1.1. Sub-Sub-Section one.
Is there any universal way to loop all Items if we don't know the menu depth?