Java多级菜单结构
我正在用 Java (Tapestry 5) 构建一个 Web 应用程序。 我想创建一个多级菜单,可以在其中显示根元素,例如在页面顶部和左侧所选元素的子元素。
为了实现这一点,我正在考虑使用这样的树结构:
public class SiteMap {
private List<MenuItem> root;
public class MenuItem {
private String 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;
}
}
}
现在,如果我想基于树中某处的 1 个父项(只有 pageFileName - String)的子项构建一个菜单,该怎么办?我必须递归地遍历树才能根据 pageFileName (String) 找到此父项,这似乎不是一个好方法。
这是(使用树结构)实现此目的的正确方法吗?或者有更好的选择吗? 任何想法和提示表示赞赏!
提前致谢!
内森
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 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这样做没有什么问题,代码运行得非常快,特别是因为您不会有数百万个菜单条目。
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.
为什么不为父级和子级使用 MenuItem 并保留每个子级对其父级的引用?
Why not use MenuItem for both parent and children and keep a reference from each child to its parent?