java中的尾递归 [英] Tail Recursion in java

查看:721
本文介绍了java中的尾递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是显示尾递归的一个很好的例子吗?

Is this a good example to show tail recursion?

public printName(){
    System.out.println("Smith");
    printName();
}

我不打算在现实生活中这样做,但我把它放了作为我考试的一个例子。这是正确的吗?

I'm not intending to do this in real life, but i put this as an example for my exam. Is this one correct?

推荐答案

不,原因有两个:


  • 尾递归仅在编译器支持它时才有用(尾调用优化)。在Java中,它仍将以 StackOverflowError结束

  • tail recursion is only valuable when compiler supports it (tail call optimization). In Java it will still end with StackOverflowError

显示一些停止条件会很好。你的代码相当于永远循环运行。

it would be nice to show some stop condition. Your code is equivalent to loop running forever.

在Scala中考虑几乎相同的代码,唯一的区别是Scala编译器执行尾调用优化并且循环永远运行:

Consider almost identical code in Scala, the only difference is that Scala compiler will perform tail call optimization and the loop runs forever:

def printName() {
  println("Smith"); 
  printName()
}

这篇关于java中的尾递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆