java.lang.StackOverflowError due to recursion

前端 未结 10 2278
南方客
南方客 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 06:48

    When properly used, recursion will not produce a StackOverflowError. If it does, then your base case is not being triggered, and the method keeps calling itself ad infinitum. Every method call that does not complete remains on the stack, and eventually it overflows.

    But loops don't involve method calls by themselves, so nothing builds up on the stack and a StackOverflowError does not result.

提交回复
热议问题