MichaelBlog

double i = Double.MAX_VALUE; while(i == i + 1){ System.out.print ("学无止境");};

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

Java递归与迭代

java 递归方法recursive

递归:直接或间接调用自身方法。
实质:不用循环控制的重复。

eg1:计算阶乘


public static long factorial(int n) {
    if (n == 0) 
      return 1;
    else
      return n * factorial(n - 1); 
  }

🎈注意:若递归不能使问题简化并且收敛,就会出现无限递归,导致StackOverflowError。

eg1:斐波那契数列Fibonacci

数列:0   1   2   3   4  ...
下标:0   1   2   3   4  ...
fib(0) = 0;
fib(1) = 1;
fib(index)  = fib(index - 2) + fib(index - 1 );
且index>=2
public static long fib(long index) {
    if (index == 0) // Base case
      return 0;
    else if (index == 1) // Base case
      return 1;
    else  // Reduction and recursive calls
      return fib(index - 1) + fib(index - 2);
  }
  

迭代iteration

java迭代器Iterator

import java.util.ArrayList;
import java.util.Iterator; //迭代器

public class Test {
    public static void main(String[] args) {

        // 创建集合
        ArrayList<String> alphabet = new ArrayList<String>();
        alphabet.add("aaa");
        alphabet.add("bbb");
        alphabet.add("ccc");
        alphabet.add("ddd");

        // 获取迭代器
        Iterator<String> it = alphabet .iterator();

        // 输出集合中的第一个元素
        System.out.println(it.next());
        /*
		// 输出集合中的所有元素
        while(it.hasNext()) {
            System.out.println(it.next());
        }
		*/
    }
}

含义区别: 递归是重复调用函数自身实现循环(自己传给自己),迭代是函数内某段代码实现循环。
结构区别: 递归用 选择结构 ,迭代用 重复结构。递归通过重复函数调用实现重复, 迭代显式使用重复结构。

posted on   Michael_chemic  阅读(155)  评论(0编辑  收藏  举报

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示