---
# System prepended metadata

title: Java - 2 ways of Fibonacci Series
tags: [Java, Basic Java]

---

# Java - 2 ways of Fibonacci Series
###### tags: `Java` `Basic Java`

## Loop and List(or Array)
直接放進list中速度較快
```
    public static int arrayListFibo(int n) {
        ArrayList<Integer> arrayList = new ArrayList<>();
        arrayList.add(0, 0);
        arrayList.add(1, 1);
        arrayList.add(2, 1);
        for (int i = 3; i < n + 1; i++) {
            arrayList.add(i,arrayList.get(i - 1) + arrayList.get(i - 2));
        }
        return arrayList.get(n);
    }
```


---


## Recursion
每次跑都要經過一次遞迴，速度較慢
```
    public static int recursiveFibo(int n) {
        if (n == 0) {
            return 0;
        }
        if (n == 1 || n == 2) {
            return 1;
        }
        return recursiveFibo(n - 1) + recursiveFibo(n - 2);

    }
```
## Let's print
```
    public static void printRecursiveFibo(int n) {
        for (int i = 0; i < n + 1 ; i++) {
            System.out.print(recursiveFibo(i) + " ");
        }
    }

    public static void printArrayListFibo(int n) {
        for (int i = 0; i < n + 1 ; i++) {
            System.out.print(arrayListFibo(i) + " ");
        }

    }
```
### result:
```
    public static void main(String[] args) {

        printRecursiveFibo(10);
        System.out.println();
        printArrayListFibo(10);


    }
```
> 0 1 1 2 3 5 8 13 21 34 55 
0 1 1 2 3 5 8 13 21 34 55 

## Complete Code
```
import java.util.ArrayList;
public class Fibonacci {

    public static void main(String[] args) {

        printRecursiveFibo(10);
        System.out.println();
        printArrayListFibo(10);


    }

    public static int arrayListFibo(int n) {
        ArrayList<Integer> arrayList = new ArrayList<>();
        arrayList.add(0, 0);
        arrayList.add(1, 1);
        arrayList.add(2, 1);
        for (int i = 3; i < n + 1; i++) {
            arrayList.add(i,arrayList.get(i - 1) + arrayList.get(i - 2));
        }
        return arrayList.get(n);
    }


    public static int recursiveFibo(int n) {
        if (n == 0) {
            return 0;
        }
        if (n == 1 || n == 2) {
            return 1;
        }
        return recursiveFibo(n - 1) + recursiveFibo(n - 2);

    }

    public static void printRecursiveFibo(int n) {
        for (int i = 0; i < n + 1 ; i++) {
            System.out.print(recursiveFibo(i) + " ");
        }
    }

    public static void printArrayListFibo(int n) {
        for (int i = 0; i < n + 1 ; i++) {
            System.out.print(arrayListFibo(i) + " ");
        }

    }

}
```