以下是一些示例代码,这些代码使用递归在层次结构中列出了它们。Item类具有子级列表。诀窍是将任何新的孩子添加到正确的父母中。这是我为此创建的方法:
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;}可能有一种更有效的方法,但这可行。
然后,当您要将新项目添加到层次结构时,请执行以下操作:
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);}对于实际的显示,我只是传递了一个“选项卡级别”,其中说出了选项卡输入的距离,然后为每个孩子增加它,如下所示:
public String toStringHierarchy(int tabLevel){ StringBuilder builder = new StringBuilder(); for(int i = 0; i < tabLevel; i++){ builder.append("t"); } builder.append("-" + name); builder.append("n"); for(Item nextChild : children){ builder.append(nextChild.toStringHierarchy(tabLevel + 1)); } return builder.toString();}这给了我这个:
-electronics -Television -21inch -Test -23inch -LCD display -player -mp3player -vcd player -hd quality -dvd player



