java - 使用此问题中提供的数据创建递归 TreeView?
问题描述
我有一个 Treeview TreeView<MyType>
,我想从MyType
根对象递归地填充它。类的结构MyType
如下:
public class MyType {
private Set<MyType> children = new HashSet<>();
public Set<MyType> getChildren() {
return children;
}
public void setChildren(Set<MyType> children) {
this.children = children;
}
}
如您所见,MyType
根/父级具有相同类型的子级,而这些子级也可以具有相同类型的子级。在实践中,根与其最远的继承者之间的深度不大于 1000 级。
我想用与存储在根文件中的数据相同的树结构中的TreeView<MyType>
树项递归地填充 Treeview。TreeItem<MyType>
MyType
这是我到目前为止尝试过的,但它不起作用:
void buildTree(MyType parent, TreeItem<MyType> result) {
for (MyType child : parent.getChildren()) {
if (child.getChildren() == null || child.getChildren().isEmpty()) {
result.getChildren().add(new TreeItem<MyType>(child));
}
else {
TreeItem<MyType> tmp = new TreeItem<>(child);
buildTree(child, tmp);
}
}
}
是否可以使用提供的数据结构进行填充?
解决方案
更方便
A. 返回TreeItem
s 而不是同时传递MyType
和传递TreeItem
给递归方法调用。
B. 将叶子视为绝症,而不是在叶子的父母处处理绝症
这允许您编写以下代码:
private TreeItem<MyType> buildSubtree(MyType root) {
TreeItem<MyType> result = new TreeItem<>(root);
if (root.getChildren() != null) {
for (MyType child : root.getChildren()) {
result.getChildren().add(buildSubtree(child));
}
}
return result;
}
推荐阅读
- raspberry-pi - Grafana 在尝试配置 InfluxDB 时给出错误消息“服务器错误”
- .net-core - .NET Core 应用程序将 Azure Redis 缓存与负载均衡器结合使用
- javascript - 刷新页面时 SessionStorage 不起作用
- typescript - MS ADAL 集成:身份验证失败错误:用户取消了 Ionic 4 上的流 RequestId
- android - android上传图片在facebook messenger SDK webview中不起作用
- python - 使用文本文件创建字典时出现问题,该字典以单词长度为键,而实际单词本身为 Python 中的值
- fullcalendar - Fullcalendar 在事件中添加图标或文本
- excel - 根据相邻单元格中的值列表获取同一单元格中的多个值
- c++ - C ++中的模板构造函数参数基类型检查
- python - 在大系数矩阵中找到高相关性