java - 将递归方法更改为迭代方法

标签 java recursion

我有递归函数,效果很好。问题是当行数很大时它会出现 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/

相关文章:

java - Netbeans IDE - 如何更改 ANT 脚本的默认运行目标?

python - Scala:递归修改元素/列表的列表

java - JAVA中遍历JSON数据

java - Jersey Rest Get 具有特殊特征

java - 每个 tomcat 服务器只有一个 servlet 对象吗?

java - 检查该方法是否已使用该输入执行的方法

Java对象不能通过递归通过ref传递

python - 无限猴子定理 : Maximum Recursion Depth exceeded

JavaScript 在 JSON 对象中递归搜索

java - eclipselink setter 更新提示