2013-06-04 160 views
0

我想在recursivly build itemlist中找到一个名字。 项目可以有子项目可以有子项目等递归名称搜索

它的第一级工作。对于更深的层次,正确找到的名称/ 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; 
    } 

回答

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; 
} 
+0

感谢;)它的工作 – Siser

0

你不指定返回值这里

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

其实你并不需要参数名称 - 仅返回名称null每次调用

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; 
} 
+0

这是错的,我编辑。 – sp00m

+0

@ sp00m所以你没有 - 我发现你的原始错误,并在这里发布了一个修正版本。取消删除你的内容,我会加注它。 – Alnitak