任何人都可以用递归逻辑来帮助我吗?我有一个迭代器对象,我正在迭代使用while循环。然后在每个迭代的对象中,我再次必须迭代等等。
private void handleRecursiveMethod(someMethod) {
Iterator<Sometype> methods=doingSomething(someMethod));
while(methods.hasNext()){
printingDetailsAboutThisMethod(methods.next())
// Again with each method I have to do same
// operation until methods.hasNext becomes false.
handleRecursiveMethod(methods.next());
// By calling this, it does not complete while
// loop first time.
}
}
答案 0 :(得分:1)
你的函数进入while循环,直到迭代器没有更多的条目来迭代。所以我想当你在方法结束时调用handleRecursiveMethod(methods.next());
时,应该给你一个NoSuchElementException
。
从您的示例来看,您似乎正在尝试进行深度优先遍历。所以,你的代码看起来应该像
private void handleRecursiveMethod(Sometype someMethod) {
Iterator<Sometype> methods=doingSomething(someMethod));
while(methods.hasNext()){
Sometype method = methods.next()
printingDetailsAboutThisMethod(method)
handleRecursiveMethod(method);
}
}