public interface Generator<T> {
T next();
}
public class Fibonacci implements Generator<Integer> {
private int count = 0;
private int fab(int n) {
if (n < 2)
return 1;
return fab(n - 2) + fab(n - 1);
}
@Override
public Integer next() {
return fab(count++);
}
public static void main(String[] args) {
Fibonacci fibonacci = new Fibonacci();
for (int i = 0; i < 18; i++)
System.out.print(fibonacci.next() + " ");
}
}
输出
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584
public class IterableFibonacci extends Fibonacci implements Iterable<Integer>{
private int n;
public IterableFibonacci(int count) {
this.n = count;
}
@Override
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
@Override
public boolean hasNext() {
return n > 0;
}
@Override
public Integer next() {
n--;
return IterableFibonacci.this.next();
}
};
}
public static void main(String[] args) {
for(int i : new IterableFibonacci(18))
System.out.print(i + " ");
}
}
输出
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584