所以我很好奇是否可以对 Java 实现递归限制,并在链接中发现了这段代码: Set maximum recursion depth in java
getStackTrace().length 从多少开始计数? 0还是1? “堆栈”从什么数字开始? 0 还是 1?
public class RecursionLimiter {
public static int maxLevel = 10;
public static void emerge() {
if (maxLevel == 0)
return;
try {
throw new IllegalStateException("Too deep, emerging");
} catch (IllegalStateException e) {
if (e.getStackTrace().length > maxLevel + 1)
throw e;
}
}
}
public class RecursionLimiter {
public static int maxLevel = 10;
public static void emerge() {
if (maxLevel == 0)
return;
try {
throw new IllegalStateException("Too deep, emerging");
} catch (IllegalStateException e) {
if (e.getStackTrace().length > maxLevel) {
System.out.println(e.getStackTrace().length);
throw e;
}
}
}
}
public static void main(String[] args) {
// TODO code application logic here
printRecursively(8);
}
public static void printRecursively(int n) {
RecursionLimiter.emerge();
if (n == 1) {
System.out.println(1);
return;
}
System.out.println(n);
printRecursively(n-1);
}
我使用了上面的两个类,它似乎在 printRecursively(9) [in main()]; 处停止工作。这意味着自抛出异常以来堆栈已达到 10。
后台发生了什么? 通过运行 printRecursively() ["first iteration"],它是否被添加到堆栈中?即使如此, printRecursively(9) 不应该只使用 9 个“堆栈级别”吗?
最佳答案
getStackTrace() 是一个非常慢的方法(这就是异常被视为慢的原因)。切勿将其用于正常程序流程 ( Effective Java, item 57 )。如果要实现递归限制,请为递归方法提供一个递减计数器:
public static void printRecursively(int n, int depth) {
if (depth == 0)
... stop recursing
System.out.println(n);
printRecursively(n-1, depth - 1);
}
关于java - 堆栈是从 0 开始还是从 1 开始?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55951462/