用java写的递归实现无限分类时,循环添加到list里的对象老是一个
用java写的递归实现无限分类时,循环添加到list里的对象总是一个
下面是我的代码,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;
}
------解决思路----------------------
看看这个代码试试吧。。。。
------解决思路----------------------
result每次都是new出来一个空的~~
下面是我的代码,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;
}
------解决思路----------------------
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;
}
看看这个代码试试吧。。。。
------解决思路----------------------
result每次都是new出来一个空的~~