事例代码:
package com.xt.thins_15_3; import java.util.Iterator; /**
* 泛型接口
*
* @author xue
*
* @param <T>
*/
interface Generic<T> {
public T next();
} /**
* 斐波纳契(一种整数数列),普通类实现
*
* @author xue
*
*/
class Fibonacci implements Generic<Integer> { protected static int count = 0; @Override
public Integer next() {
// TODO Auto-generated method stub
return fib(count++);
} public int fib(int n) {
if (n < 2)
return 1;
return fib(n - 2) + fib(n - 1);
}
} /**
* 迭代适配器迭代斐波纳契(一种整数数列)
*
* @author xue
*
*/
class IterableFibonacci extends Fibonacci implements Iterable<Integer> { private int size; public IterableFibonacci(int size) {
this.size = size;
count = 0;
} @Override
public Iterator<Integer> iterator() {
// TODO Auto-generated method stub
return new Iterator<Integer>() { @Override
public void remove() {
// TODO Auto-generated method stub } @Override
public Integer next() {
// TODO Auto-generated method stub
size--;
return IterableFibonacci.this.next();
} @Override
public boolean hasNext() {
// TODO Auto-generated method stub
return size > 0;
}
};
} } public class FibonacciTest {
public static void main(String[] args) {
Fibonacci fib = new Fibonacci();
for (int i = 0; i < 20; i++) {
System.out.print(fib.next() + ",");
}
System.out.println("\n------------------------------");
IterableFibonacci ifib = new IterableFibonacci(20);
for (Integer integer : ifib) {
System.out.print(integer + ",");
}
}
}