Java中递归是如何实现的 [英] How is recursion implemented in Java

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

问题描述

递归是如何在Java中实现的?我的问题是在 Java 中执行递归方法时会发生什么.我隐约明白它使用堆栈,但我正在寻找一个带有示例的清晰解释.

How is recursion implemented in Java? My question is about what happens behind when a recusrsive method is executed in Java. I vaguely understand that it uses the Stack, but i am looking for a clear explanation with example.

推荐答案

递归在 Java 中的处理方式与在其他(命令式)语言中没有太大不同.

Recursion isn't handled much differently in Java than in other (imperative) languages.

一个堆栈,它为每个方法调用保存一个堆栈框架.该堆栈是调用堆栈(或者只是堆栈",当上下文清楚地表明其含义时).栈上的元素称为栈帧".

There's a stack which holds a stack frame for every method invocation. That stack is the call stack (or simply just "stack", when the context makes it clear what is meant). The element on the stack are called "stack frames".

堆栈帧包含传入的方法参数和方法调用的局部变量(可能还有一些其他数据,例如返回地址).

A stack frame holds the method arguments passed in and the local variables of a method invocation (and possibly some other data, such as the return address).

当一个方法调用自身(或者实际上是任何方法)时,就会为新调用方法的参数和局部变量创建一个新的堆栈框架.

When a method invokes itself (or, in fact, any method) then a new stack frame is created for the parameters and local variables of the newly-called method.

在方法执行期间,代码可以访问当前(即最顶部)堆栈帧中的值.

During the method execution the code can only access the values in the current (i.e. top-most) stack frame.

这样,单个(局部)变量似乎可以同时具有许多不同的值.

This way a single (local) variable can seemingly have many different values at the same time.

除了普通方法调用之外,不会以任何其他方式处理递归,除了多个堆栈帧将同时表示同一方法的调用.

Recursion isn't handled any other way than normal method calls, except that multiple stack frames will represent invocations of the same method at the same time.

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

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