15.3 泛型接口_Fabonacci

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。