0

我想在递归构建项目列表中找到一个名称。项目可以有子项目,子项目可以有子子项目等。

对于第一级,它起作用了。对于更深层次,正确找到的名称/ID 映射会从堆栈中覆盖。由于字符串结果,我必须在最后编写 return 语句。所以我有一个心理障碍,我该如何解决这个问题。感谢您的帮助。

public String getNameForID(List<Item> top, long id, String name ) {

        for (Item i : top) {
            if (i.getId() == id) {
                name =  i.getName();
                return name;
            }else{
             this.getNameForID(i.getSubItemsList(), id,name);
            }

        }
        return name;
    }
4

3 回答 3

1

这一定是您正在寻找的:

public String getNameById(List<Item> items, long id) {
    // boundary condition
    if (items == null || items.isEmpty()) {
        return null;
    }
    // looping
    for (Item item : items) {
        // if current is
        if (item.getId() == id) {
            return item.getName();
        }
        // recursion
        String name = getNameById(item.getSubItemsList(), id);
        // if nested found
        if (name != null) {
            return name;
        }
    }
    // boundary condition
    return null;
}
于 2013-06-04T09:45:25.143 回答
1

您的递归调用也getNameForID 必须能够返回一个值。它还需要能够指示没有找到任何值,以便终止递归。

根据@sp00m 之前删除(且略有错误)的答案,试试这个:

public String getNameById(List<Item> items, long id) {

    // sanity checking conditions to terminate recursion early
    if (items == null || items.isEmpty()) {
        return null;
    }

    // iterate over collection
    for (Item item: items) {
        if (item.getId() == id) {
            return item.getName();
        } else {
            String name = getNameById(item.getSubItemsList(), id);
            if (name != null) {
                return name;
            }
        }
    }

    // final termination condition - entry wasn't in this list
    return null;
}
于 2013-06-04T09:46:17.253 回答
0

您没有将此处返回的值分配给name

this.getNameForID(i.getSubItemsList(), id,name);

实际上您不需要参数名称 - 只需在每次调用中返回名称null

于 2013-06-04T09:45:54.883 回答