用java写的递归实现无限分类时,循环添加到list里的对象总是一个

Hunter_first 2015-04-05 03:36:21
下面是我的代码,list是我从数据库取出分类表的所有数据,字段为shopcategoryid,pid,shopcategory。我想取出其中我想要的记录,于是遍历list,用另外一个list result来存它,但是每次只能获得第一个对象,不知道哪里出了问题
public List<ShopCategory> getCategory(List<ShopCategory> list, int pid, int level)
{
List<ShopCategory> result = new ArrayList<ShopCategory>();
for(ShopCategory categorylist : list)
{
if(categorylist.getPid()==pid)
{
ShopCategory cate = new ShopCategory();
cate.setPid(categorylist.getPid());
cate.setShopcategoryid(categorylist.getShopcategoryid());
cate.setShopcategory(categorylist.getShopcategory());
result.add(cate);
getCategory(list,categorylist.getShopcategoryid(), level+1);
}

}
return result;
}
...全文
913 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
scmod 2015-04-06
  • 打赏
  • 举报
回复
result每次都是new出来一个空的~~
microhex 2015-04-06
  • 打赏
  • 举报
回复

 List<ShopCategory> result = new ArrayList<ShopCategory>();
public List<ShopCategory> getCategory(List<ShopCategory> list, int pid, int level)  
    {  
    for(ShopCategory categorylist : list)  
        {  
        if(categorylist.getPid()==pid)  
            {  
            ShopCategory cate = new ShopCategory();
            cate.setPid(categorylist.getPid());
            cate.setShopcategoryid(categorylist.getShopcategoryid());
            cate.setShopcategory(categorylist.getShopcategory());
            result.add(cate);
            getCategory(list,categorylist.getShopcategoryid(), level+1);  
            }  
        
        }
        return result;  
    }
看看这个代码试试吧。。。。
Hunter_first 2015-04-06
  • 打赏
  • 举报
回复
问题已经解决,按2楼的方法解决了,调试的时候竟然没注意!顺便问一下如果我不想用递归实现,该怎么做呢,感觉递归虽然简单但是效率比较低

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧