事例代码:

 1 package com.xt.thins_15_3;
 2 
 3 import java.util.Iterator;
 4 
 5 /**
 6  * 泛型接口
 7  * 
 8  * @author xue
 9  * 
10  * @param <T>
11  */
12 interface Generic<T> {
13     public T next();
14 }
15 
16 /**
17  * 斐波纳契(一种整数数列),普通类实现
18  * 
19  * @author xue
20  * 
21  */
22 class Fibonacci implements Generic<Integer> {
23 
24     protected static int count = 0;
25 
26     @Override
27     public Integer next() {
28         // TODO Auto-generated method stub
29         return fib(count++);
30     }
31 
32     public int fib(int n) {
33         if (n < 2)
34             return 1;
35         return fib(n - 2) + fib(n - 1);
36     }
37 }
38 
39 /**
40  * 迭代适配器迭代斐波纳契(一种整数数列)
41  * 
42  * @author xue
43  * 
44  */
45 class IterableFibonacci extends Fibonacci implements Iterable<Integer> {
46 
47     private int size;
48 
49     public IterableFibonacci(int size) {
50         this.size = size;
51         count = 0;
52     }
53 
54     @Override
55     public Iterator<Integer> iterator() {
56         // TODO Auto-generated method stub
57         return new Iterator<Integer>() {
58 
59             @Override
60             public void remove() {
61                 // TODO Auto-generated method stub
62 
63             }
64 
65             @Override
66             public Integer next() {
67                 // TODO Auto-generated method stub
68                 size--;
69                 return IterableFibonacci.this.next();
70             }
71 
72             @Override
73             public boolean hasNext() {
74                 // TODO Auto-generated method stub
75                 return size > 0;
76             }
77         };
78     }
79 
80 }
81 
82 public class FibonacciTest {
83     public static void main(String[] args) {
84         Fibonacci fib = new Fibonacci();
85         for (int i = 0; i < 20; i++) {
86             System.out.print(fib.next() + ",");
87         }
88         System.out.println("\n------------------------------");
89         IterableFibonacci ifib = new IterableFibonacci(20);
90         for (Integer integer : ifib) {
91             System.out.print(integer + ",");
92         }
93     }
94 }