java.lang.StackOverflowError due to recursion

前端 未结 10 2253
南方客
南方客 2020-12-03 05:59

My problem is that I usually get a java.lang.StackOverflowError when I use recursion. My question is - why does recursion cause stackoverflow so much more than loops do, and

10条回答
  •  抹茶落季
    2020-12-03 06:36

    why does recursion cause stackoverflow so much more than loops do

    Because each recursive call uses some space on the stack. If your recursion is too deep, then it will result in StackOverflow, depending upon the maximum allowed depth in the stack.

    When using recursion, you should be very careful and make sure that you provide a base case. A base case in recursion is the condition based on which the recursion ends, and the stack starts to unwind. This is the major reason of recursion causing StackOverflow error. If it doesn't find any base case, it will go into an infinite recursion, which will certainly result in error, as Stack is finite only.

提交回复
热议问题