我有递归函数,效果很好。问题是当行数很大时它会出现 stackoverflow 错误。我想将其迭代,可能使用 for 循环。需要一些帮助来做到这一点。
private TreeSet validate(int curLine, TreeSet errorSet) {
int increment = 0;
int nextLine = 0;
if (curLine == lines.length || errorSet.size() != 0) {
return errorSet;
} else {
String line = lines[curLine];
//validation starts. After validation, line is incremented as per the requirements
increment = 1 //As per requirement. Depends on validation results of the line
if (increment > 0) {
try{
Thread.currentThread().sleep(100);
}catch(Exception ex){
System.out.println(ex);
}
nextLine = (curLine + increment);
validate(nextLine, errorSet);
}
}
return errorSet;
}
海报对该方法的描述:
该方法确实验证文本行,如果该行有效,这些行包含必须跳过多少行的说明。因此,如果该行有效,则将使用增量跳过许多行。如果该行无效,则增量将为 0。
最佳答案
我不确定为什么这首先是递归的。这非常适合使用 FOR 循环。使用类似这样的东西:
private TreeSet validate(int curLine, TreeSet errorSet) {
int increment = 0;
if (errorSet.size() != 0)
return errorSet;
for (int curLine = 0; curLine < lines.Length; curLine += increment)
{
// put your processing logic in here
// set the proper increment here.
}
}
如果增量始终为 1,则可以使用 curr++
而不是 curLine +=增量
关于java - 将递归方法更改为迭代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11725280/