gpt4 book ai didi

java - 如何遍历嵌套 java 对象列表?

转载 作者:行者123 更新时间:2023-12-02 12:28:10 26 4
gpt4 key购买 nike

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

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

childItem 还可以包含子项列表。我的问题是,我可以迭代所有级别的 childItems 吗?

现在我的代码如下所示:

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 不为空。您可以通过将 getElementByOpenedRowID 设置为 SearchItemType 上的方法来解决此问题,这意味着不需要传递 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;
}

关于java - 如何遍历嵌套 java 对象列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45397928/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com