JAVA泛型接口

事例代码:

 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 }

 

转载于:https://www.cnblogs.com/wubingshenyin/p/4424422.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值