编程语言
首页 > 编程语言> > java – 如何避免递归函数的StackOverflowError

java – 如何避免递归函数的StackOverflowError

作者:互联网

我正在编写一个函数,可以调用自己大约5000次.当然,我得到一个StackOverflowError.有什么方法可以用相当简单的方式重写这段代码吗?:

void checkBlocks(Block b, int amm) {

    //Stuff that might issue a return call

    Block blockDown = (Block) b.getRelative(BlockFace.DOWN);
    if (condition) 
        checkBlocks(blockDown, amm);


    Block blockUp = (Block) b.getRelative(BlockFace.UP);
    if (condition) 
        checkBlocks(blockUp, amm);

    //Same code 4 more times for each side

}

那么,我们可以称之为功能的深度有多大限制?

解决方法:

使用显式堆栈对象和循环,而不是调用堆栈和递归:

void checkBlocks(Block b, int amm) {
  Stack<Block> blocks = new Stack<Block>();
  blocks.push(b);
  while (!blocks.isEmpty()) {
    b = blocks.pop();
    Block blockDown = (Block) b.getRelative(BlockFace.DOWN);
    if (condition)
      blocks.push(block);
    Block blockUp = (Block) b.getRelative(BlockFace.UP);
    if (condition) 
      blocks.push(block);
  }
}

标签:java,stack-overflow
来源: https://codeday.me/bug/20191005/1857168.html