递归Java堆栈溢出
我创建了一个有意触发StackOverflowError
的应用程序,它表现出一些奇怪的行为。我的应用程序依赖于递归方法,这种方法有终止递归的基本情况:它在while
循环中增加一个变量,直到其值等于或超过硬编码的目标值。奇怪的是,触发堆栈溢出所需的最小目标值在不同的运行中并不一致。为什么会这样
以下是代码:
public class MyClass {
private static MyClass appOne4 = new MyClass();
private static int i = 0;
public void causeStackoverflowException() {//Recursive Method
System.out.println(i);
while (i<12000) {
i++; //This works since variable "i" is static
causeStackoverflowException();
}
}
public static void main(String[] args) {
appOne4.causeStackoverflowException();
}
}
更新代码
public class MyClass {
private static MyClass appOne4 = new MyClass();
private static int i = 0;
public static void main(String[] args) {
appOne4.causeStackoverflowException(i);
}
public int causeStackoverflowException(int myI) {//Recursive Method
System.out.println(myI);
if(myI==10460) {//12000
return myI;
}
if (myI<12000) {
myI++; //This works since variable "i" is static
return causeStackoverflowException(myI);
}
return -1;////ERROR
}
}
共 (0) 个答案