如何遍历嵌套java对象列表?
我有一个对象类,它本身包含一个列表。。。大概是这样的:如何遍历嵌套java对象列表?,java,arraylist,nested,Java,Arraylist,Nested,我有一个对象类,它本身包含一个列表。。。大概是这样的: public class SearchItemType implements Serializable { protected List<SearchItemType> childItem; } public SearchItemType getElementByOpenedRowID(SearchItemType gridResult, String selectedRowId, Boolean found) {
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;
}
非常感谢。您可以通过递归实现这一点:
public void iterate(SearchItemType type) {
// Do something with type
for (SearchItemType child in type.childItem) {
iterate(child);
}
}
是的,只要childItem不为null,并且其中的对象具有非null值,就可以在任何级别上迭代childItem对象
在LinkedList的数据结构实现中,LinkedList中的每个节点都有数据字段链接到其他节点,如果是Java,则链接到其他节点
它也被称为自引用对象,这意味着对象指向类似类型的对象
只要列表中有非空值,就可以在任何级别进行迭代
Java中的数据结构也是以类似的方式实现的。
请查看此代码段中的节点类:
您希望递归遍历子对象,如下所示:
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;
}
有一个错误:在方法的开头,您设置了SearchItemType元素=newsearchItemType;但当您递归时,请检查null。元素永远不会为空。您可以通过在开始时将其设置为null来解决此问题,但我对您的代码有一些建议: 不要将查找到的值分配给元素并设置查找标志,只要找到对象就返回它。在方法的末尾返回null。这将更加清楚。 即使父对象是搜索到的对象,当前也将执行对子对象的迭代和检查。实际上,您可以完全删除这个循环,因为它是由下面的递归步骤处理的。 为什么要将find作为参数传递?如果您将其传递为true,那么拥有它就没有意义,因此如果您确实需要它,只需在方法中实例化它。 确保检查gridResult不为null。您可以通过使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;
}
您显示的代码有什么问题?它似乎正是你想要实现的。