我很好奇递归在 jvm 中是如何工作的。遵循示例。首先计算给定数字的阶乘。
public class Factorial {
public int factorial(int n) {
System.out.println("Factorial: " + n);
if ( n < 2) {
return 1;
}
return n * factorial(n - 1);
}
执行以下测试
@Test
public void test_factorial() {
Factorial fact = new Factorial();
System.out.println(fact.factorial(3));
}
显示
3
2
1
看起来很明显,方法调用被放入堆栈,执行到达 n == 1 并返回。现在,我尝试计算斐波那契数。
public int fibo(String name, int n) {
System.out.println("fibo: " + name + " " + n);
if (n < 2 ) {
return n;
}
return fibo ("left", n - 1) + fibo ("right", n - 2);
}
执行测试
@Test
public void test_fibonacci() {
Fibo fibo = new Fibo();
assertEquals(8, fibo.fibo("start",6));
}
打印以下内容
fibo: start 6
fibo: left 5
fibo: left 4
fibo: left 3
fibo: left 2
fibo: left 1
fibo: right 0
fibo: right 1
fibo: right 2
fibo: left 1
fibo: right 0
fibo: right 3
fibo: left 2
fibo: left 1
fibo: right 0
fibo: right 1
fibo: right 4
fibo: left 3
fibo: left 2
fibo: left 1
fibo: right 0
fibo: right 1
fibo: right 2
fibo: left 1
fibo: right 0
我的问题是在这个例子中调用方法并将其放入堆栈的规则是什么?