在以下代码中,变量 levelsToGo
在递归调用 getAllStringNames()
时意外更新。当它返回到堆栈弹出时,我得到的是传递到递归调用中的levelsToGo的值,而不是之前存在的值。
public List<String> getAllStringNames(Student p, Integer levelsToGo)
{
List<String> employeeSet = new ArrayList<String>();
for(Student child : p.getAllSubjects())
{
employeeSet.add(child.getRoll());
if(levelsToGo > 0)
studentChilds.addAll(getAllStringNames(child, --levelsToGo))
}
return employeeSet;
}
我第一次通过student1时,levelsToGo
为1,student1有1个 child 。它递归调用并将levelsToGo设置为0。当它回到第一次迭代时,我们发现值仍然是0。它应该是原始值1。
最佳答案
当您在 getAllStringNames()
方法调用中使用 levelsToGo
时,您会递减它。表达式 --levelsToGo
表示将 levelsToGo
的值减一,将其存储回 levelsToGo
,然后在方法调用中使用它。
相反,你应该写
studentChilds.addAll(getAllStringNames(child, levelsToGo - 1));
关于java - 在递归函数中参数值根据向下递归值而变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35709246/