【发布时间】:2012-11-29 14:13:42
【问题描述】:
我有一个可展开的树(在 HTML 页面中):
+ Category 1
- Category 2
+ Subcategory 1
- Subcategory 2
|- Foo
|- Bar
|- Link 42
由结构表示(在后端定义):
class Demo {
static ImmutableList<Item> sample() {
return ImmutableList.of(
new Item("Category 1", ImmutableList.of(
new Item("Some link title", "resource_id_1"),
new Item("Another link title", "resource_id_2"))),
new Item("Category 2", ImmutableList.of(
new Item("Subategory 1", ImmutableList.of(
new Item("Another link title", "resource_id_3"))),
new Item("Subcategory 2", ImmutableList.of(
new Item("Foo", "resource_id_1"),
new Item("Bar", "resource_id_2"),
new Item("Link 42", "resource_id_42"))))));
}
}
Item 定义如下:
public class Item {
private String readableName;
private String resourceId;
private ImmutableList<Item> children;
Item(String name, String resourceId) {
this.readableName = name;
this.resourceId = resourceId;
}
Item(String name, ImmutableList<Item> children) {
this.readableName = name;
this.children = children;
}
public String getReadableName() {
return readableName;
}
public String getResourceId() {
return resourceId;
}
public ImmutableList<Item> getChildren() {
return children;
}
}
resourceId 可以有不同的可读名称,并且可以在整个结构中多次放置,但在当前类别/子类别中只能放置一次。
当前,当用户点击链接或写入 URL 时,资源被加载(例如链接 Foo 映射到 /showResource?id=resource_id_1:uniqe_magic_id)并展开树。它的工作原理只是因为 hack - 前端创建自己的结构副本,将一些 :uniqe_magic_id 字符串附加到每个资源 id(每个叶子),并且在向后端发送请求时,它会删除魔术部分。 :uniqe_magic_id 仅由前端用于扩展上面显示的树中的适当项目。对我来说,这似乎是一个巧妙的解决方案(我正在重构这段代码并删除了 cleanId 方法,我认为这不是必需的,但在向后端发送请求之前正在剥离魔法......)我正在寻找一个更好的方法。
我可以同时修改前端和后端。我想到了某种带有节点的树,例如:
class Node {
Node next;
Node child;
String readableName;
String resourceId;
String someUniqueHash;
}
并使用someUniqueHash。
有没有更好的方法来实现相同的结果而不在前端复制整个结构?
【问题讨论】:
-
我认为这不会解决您的问题,但是由于您不需要在任何级别强制执行重复值,您是否考虑过使用 LinkedHashSet(或其不可变)而不是 List?
-
List最初在这里用于表示它以某种方式排序并且Items 到目前为止还没有 hashCode / equals,但这是一个小(且有用)的建议,实际上并没有解决我的问题。 -
只在后端维护结构怎么样。在前端显示一棵树并始终从服务器请求从单击的节点开始的子树?此外,使用weakhashmap 可能很有用。
-
当您获得被点击节点的子树时,也可能会为一级节点获取子节点。
-
通过
new Item(String, ImmutableList<Item>)构造函数将孩子的id改为父母的id怎么办?这样您将拥有唯一的 ID,无需复制或更改结构。
标签: java data-structures tree