實現Iterable接口產生Fibonacci 數列

//接口類
public interface Generator<T>{
	T next();
}
//實現接口類 產生數列
public class Fibonacci implements Generator<Integer>{
	private int count=0;
	public Integer next(){
		return fib(count++);
	}
	private int fib(int n ){
		if (n<2) return 1;
		return fib(n-2)+fib(n-1);
	}
	public static void main(String[] args) {
		Fibonacci gen = new Fibonacci();
		for (int i=0;i<18 ;i++ ) {
			System.out.println(gen.next()+" ");
		}
	}
}

//實現Iterable接口產生Fibonacci 數列,建立適配器實現所需接口
import java.util.*;
public class IterableFibonacci extends Fibonacci implements Iterable<Integer>{
	private int n=0;
	public IterableFibonacci(int count){n=count;}
	public Iterator<Integer>iterator(){
		
		return new Iterator<Integer>(){
               
                //末端哨兵,判斷什麼時候中止    
		public boolean hasNext(){
			return n>0;
			}
		public Integer next(){
			n--;
			return IterableFibonacci.this.next();
		}
		public void remove(){
			throw new UnsupportedOperationException();
		}

		};
	}


	public static void main(String[] args) {
	
		for (int i: new IterableFibonacci(18) ) {
			System.out.println(i+" ");
		}
		
	}
}
相關文章
相關標籤/搜索