简体   繁体   中英

Design patterns: Iterator pattern

    public BigDecimal next() {

        for (int i = 1; i < 100; i++) {
            BigDecimal cur = new BigDecimal(1);
            BigDecimal prev = new BigDecimal(0);

            final BigDecimal next = cur.add(prev);
            prev = cur;
            cur = next;
        }

        return cur;
    }

Could not implement Bigdecimal in this for loop to get Fibonacci numbers

In your code, hasNext is always false. This tells the consumer of the iterator that we reached the end of the iteration.

This is what you want to achieve

I replaced all BigDecimal references with Integer. If you want to keep as it then needs to make some small changes.

//This is class with main method
import java.util.Iterator;

public class IteratorPattern {
public static void main(String[] args) {
    int n = 10;
    FibonacciSequence fibonacciSequence = new FibonacciSequence(n);

    System.out.println("iteration using iterator for-loop");

    //iteration using iterator for-loop
    for (Integer fibonacciNumber : fibonacciSequence) {
        System.out.println(fibonacciNumber);
    }

    System.out.println("iteration using iterator");

    //iteration using iterator
    Iterator<Integer> iterator = fibonacciSequence.iterator();
    while (iterator.hasNext()) {
        System.out.println(iterator.next());
    }
}
}

class FibonacciSequence implements Iterable<Integer>, Iterator<Integer> {

private final Integer n;
private Integer a;
private Integer b;
private int c = 1;

FibonacciSequence(Integer n) {
    this.n = n;
}

@Override
public Iterator<Integer> iterator() {
    return new FibonacciSequence(n);
}

@Override
public boolean hasNext() {
    return c <= n;
}

@Override
public Integer next() {
    c++;
    if (a == null && b == null) {
        a = 0;
        return 0;
    } else if (b == null) {
        b = 1;
        return b;
    } else if (a == 0 && b == 1) {
        a = 1;
        return b;
    }
    Integer temp = b;
    b = b + a;
    a = temp;
    return b;
}
}

Output:

 iteration using iterator for-loop
0
1
1
2
3
5
8
13
21
34
iteration using iterator
0
1
1
2
3
5
8
13
21
34

Now the point is what changes I made.

  1. As told by @Tom S. your hasNext method should return false if the count reaches to n.

  2. I changed logic in the next method. Take a look at it.

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