我正在尝试从其 ID 中检索类别对象。 类别是可以包含其他类别和帖子的层次类。 我的实现是递归的:
public static AAbstarctCategory getCategory(ACategory category, String id) {
if (id == category.id) {
return category;
}
else if (category.categories.containsKey(id)) {
return category.categories.get(id);
}
else if (category.posts.containsKey(id)) {
return category.posts.get(id);
}
else {
for (ACategory c : category.categories.getArray()) {
getCategory(c,id);
}
}
return null;
}
问题是该函数总是返回 null... 请提出建议:)
最佳答案
您没有使用递归调用返回的值。
改变
for (ACategory c : category.categories.getArray()) {
getCategory(c,id);
}
至
for (ACategory c : category.categories.getArray()) {
AAbstarctCategory cat = getCategory(c,id);
if (cat != null)
return cat;
}
关于java - 递归函数总是返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32624009/