Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is some sample code that lists them in a hierarchy using recursion. The Item class has a List of children. The trick is adding any new children to the right parent. Here is the method I created to do this:</p> <pre><code>public Item getItemWithParent(int parentID){ Item result = null; if(this.categoryID == parentID){ result = this; } else { for(Item nextChild : children){ result = nextChild.getItemWithParent(parentID); if(result != null){ break; } } } return result; } </code></pre> <p>There is probably a more efficient way, but this works.</p> <p>Then, when you want to add new items to your hierarchy, do something like this:</p> <pre><code>public void addItem(int categoryID, String name, int parentID) { Item parentItem = findParent(parentID); parentItem.addChild(new Item(categoryID, name, parentID)); } private Item findParent(int parentID) { return rootNode.getItemWithParent(parentID); } </code></pre> <p>For the actual display, I just pass in a "tab level" that says how far to tab in, then increment it for each child like this:</p> <pre><code>public String toStringHierarchy(int tabLevel){ StringBuilder builder = new StringBuilder(); for(int i = 0; i &lt; tabLevel; i++){ builder.append("\t"); } builder.append("-" + name); builder.append("\n"); for(Item nextChild : children){ builder.append(nextChild.toStringHierarchy(tabLevel + 1)); } return builder.toString(); } </code></pre> <p>Which gives me this:</p> <pre><code>-electronics -Television -21inch -Test -23inch -LCD display -player -mp3player -vcd player -hd quality -dvd player </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload