如何遍历嵌套 Java 对象列表?



我有一个对象类,它包含一个自己的列表...像这样:

public class SearchItemType implements Serializable {
protected List<SearchItemType> childItem;
}

子项还可以连接子项的列表。我的问题是,我可以在所有级别中迭代子项吗?

现在我的代码如下所示:

public SearchItemType getElementByOpenedRowID(SearchItemType gridResult, String selectedRowId, Boolean found) {
SearchItemType element = new SearchItemType();
if (gridResult.getId().equals(selectedRowId)) {
element = gridResult;
found = true;
}
for (SearchItemType child : gridResult.getChildItem()) {
if (child.getId().equals(selectedRowId)) {
element = child;
found = true;
break;
}
}
if (!found) {
for (SearchItemType child : gridResult.getChildItem()) {
element = getElementByOpenedRowID(child, selectedRowId, found);
checkChildID(child, selectedRowId);
if (element != null) break;
}
}
return element;
}

非常感谢。

有一个错误:在方法开始时,您设置了SearchItemType element = new SearchItemType();,然后在递归时检查nullelement永远不会为空。您可以通过在开始时将其设置为null来解决此问题,但我对您的代码有一些建议:

  • 与其将找到的值分配给元素并设置found标志,只需在找到对象后立即返回即可。在方法结束时返回null.这将更加清晰。
  • 循环访问子项并检查它们当前将执行,即使父项是搜索的父项。实际上,您可以完全删除此循环,因为它由下面的递归步骤处理。
  • 为什么要将found作为参数传递?如果你把它传递true,那么拥有它就没有意义了,所以如果你真的需要它,只需在方法中实例化它。
  • 确保检查gridResult是否为空。你可以通过getElementByOpenedRowIDSearchItemType的方法来解决这个问题,这意味着gridResult不需要传递。

应用这些更改将导致:

public SearchItemType getElementByOpenedRowID(SearchItemType gridResult, String selectedRowId) {
// stop at null
if (gridResult == null) {
return null;
}
if (gridResult.getId().equals(selectedRowId)) {
return gridResult; // return once found
}
// check all of the children
for (SearchItemType child : gridResult.getChildItem()) {
// do the search again for every child
SearchItemType result = getElementByOpenedRowID(child, selectedRowId);
if (result != null) {
// return once found and sent it all the way to the top
return result;
}
}
return null;
}

你可以使用递归来做到这一点:

public void iterate(SearchItemType type) {
// Do something with type
for (SearchItemType child in type.childItem) {
iterate(child);
}
}

是的,只要childItem不为空并且其中的对象具有非空值,您就可以在任何级别迭代childItem对象。

在 LinkedList的数据结构实现中,LinkedList 中的每个节点都有Data字段链接到其他节点(在 Java 的情况下,它引用其他节点(。

它也称为自引用对象,表示指向类似类型的对象的对象。

只要列表中有非空值,就可以在任何级别进行迭代。

Java中的数据结构以类似的方式实现。 看看这个代码片段中的Node class: 使用自引用指针实现链表

您希望按如下方式递归遍历子项:

public SearchItemType getElementByOpenedRowID(SearchItemType gridResult, String selectedRowId) {
SearchItemType element = null;
if (gridResult == null) return null;
else if (gridResult.getId().equals(selectedRowId)) return gridResult;
else {
for (SearchItemType child : gridResult.getChildItem()) {
element = getElementByOpenedRowID(child, selectedRowId);
if (element != null) break;
}
}
return element;
}

最新更新