I'm building a web application in Java (Tapestry 5). I want to create a multilevel menu where I can show the root elements for example at the top of my page and the children of the selected on the left.
To implement this I was thinking to use a tree structure like this:
public class SiteMap {
private List<MenuItem> root;
public class MenuItem {
private String 开发者_Python百科pageFileName;
private String pageNavigationName;
private List<MenuItem> children;
private MenuItem parent;
public MenuItem(String pageFileName, String pageNavigationName, MenuItem parent) {
this.pageFileName = pageFileName;
this.pageNavigationName = pageNavigationName;
this.parent = parent;
}
public String getPageFileName() {
return pageFileName;
}
public String getPageNavigationName() {
return pageNavigationName;
}
public List<MenuItem> getChildren() {
return children;
}
public MenuItem getParent() {
return this.parent;
}
}
}
Now what if I want to build a menu based on the children of 1 parent item (only have the pageFileName - String) somewhere in the tree. Ill have to traverse recursively through the tree to find this parent item based on the pageFileName (String) , which seems not a good way.
Is this (using a tree structure) the right way to implement this? Or is there a better option? Any thoughts and hints are appreciated!
Thanks in advance!
Nathan
MenuItem root = null;
MenuItem curr = myMenuItem;
while(curr.getParent() != null) {
curr = curr.getParent();
}
root = curr;
There's nothing wrong with doing it that way, that code will run very fast, especailly since you aren't going to have millions of menu entries.
Why not use MenuItem for both parent and children and keep a reference from each child to its parent?
List<MenuItem> children; // empty/null for leaf nodes
MenuItem parent; // null for root nodes
精彩评论