为什么这不是一个无限递归循环?
public static void main(String[] args) {
System.out.println(isSuch(99) + " " + isSuch(100));
}
public static boolean isSuch(int n)
{
System.out.println("n is currently at "+ n);
return n > 2 && !isSuch(n - 2);
}
最佳答案
这不是无限递归循环,因为它最终会停止。它会停止,因为 &&
运算符是一个短路运算符。 JLS, Section 15.23 ,描述 &&
运算符:
The conditional-and operator && is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true.
当递归达到n
不大于2
的级别时,&&
运算符立即返回false
code> 而不评估右侧,即递归调用。这实际上使 n
不大于 2
的情况成为基本情况。然后之前的递归调用使用 !
运算符反转它,返回 true
。两个调用都返回 true
,并且 true
被打印两次。
值得注意的是,虽然这是一个相当深的递归,但堆栈大小足以处理这个问题。但发生 StackOverflowError
并不一定是无限递归循环。它所需要的只是递归得足够远。调用 isSuch(99999)
足以在我的盒子上导致 StackOverflowError
。
此外,如果您使用非短路运算符 &
而不是 &&
,那么这将是一个无限递归循环,并且会出现 StackOverflowError无论最初传递给
。isSuch
的数字是什么,都会发生
关于java - 为什么这会返回 true true 而不会堆栈溢出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31462275/