简体   繁体   中英

Tail Recursion in 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?

No, for two reasons:

  • 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.

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()
}

A better example of tail recursion would be something like this:

public printName(int level){
    if( level <= 0 )
         return;
    System.out.prntln("Smith");
    printName(--level);
}

This examples includes the important part where the recursion is terminated.

Besides of this: As other answers already noted: Since Java does not optimize tail-recursion, there is no point in using it in this language. So you basically end up to optimize your algorithm yourself - by making it iterative. That's the point of tail-recursion: It can be proved, that any tail-recursive algorithm can be transformed into an iterative algorithm.

我会说这是尾递归的一个例子,因为你在程序的尾部递归:)但我不认为JVM会优化它,这可能是你想要的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM