今天学习了用递归来解决迷宫的路线问题,突然想到一个问题:
递归是通过栈来实现的,那么会不会递归到一定次数无法递归了呢?
于是我在CSDN上找到这篇文章 文章地址
并用类似的代码试了一下
public static void recursion(int i)
{
System.out.println("This is "+i+"recursion");
recursion(i+1);
}
结果是这样的
his is 6013recursion
This is 6014recursion
This is 6015recursion
This is 6016recursion
This is 6017recursion
This is 6018recursion
This is 6019recursion
Exception in thread "main" java.lang.StackOverflowError
显示的异常是栈满了。于是继续按照那位博主所说,往里头加了个无意义的循环
public static void recursion(int i)
{
System.out.println("This is "+i+"recursion");
for (int j = 0; j < 1000; j++) {
}
recursion(i+1);
}
}
结果居然是这样的
This is 29659recursion
This is 29660recursion
This is 29661recursion
This is 29662recursion
This is 29663recursion
This is 29664recursion
This is 29665recursion
Exception in thread "main" java.lang.StackOverflowError
本来六千次的递归居然变成了快三万次,而那位博主的递归次数却是从6000变成了3000。对此感到疑惑,等以后对JVM深入了解后再来看看