2015-04-20 15:36:01 -07:00
|
|
|
|
//: generics/IterableFibonacci.java
|
2015-05-29 14:18:51 -07:00
|
|
|
|
// <20>2015 MindView LLC: see Copyright.txt
|
2015-04-20 15:36:01 -07:00
|
|
|
|
// Adapt the Fibonacci class to make it Iterable.
|
|
|
|
|
import java.util.*;
|
|
|
|
|
|
|
|
|
|
public class IterableFibonacci
|
|
|
|
|
extends Fibonacci implements Iterable<Integer> {
|
|
|
|
|
private int n;
|
|
|
|
|
public IterableFibonacci(int count) { n = count; }
|
2015-05-05 11:20:13 -07:00
|
|
|
|
@Override
|
2015-04-20 15:36:01 -07:00
|
|
|
|
public Iterator<Integer> iterator() {
|
|
|
|
|
return new Iterator<Integer>() {
|
2015-05-05 11:20:13 -07:00
|
|
|
|
@Override
|
2015-04-20 15:36:01 -07:00
|
|
|
|
public boolean hasNext() { return n > 0; }
|
2015-05-05 11:20:13 -07:00
|
|
|
|
@Override
|
2015-04-20 15:36:01 -07:00
|
|
|
|
public Integer next() {
|
|
|
|
|
n--;
|
|
|
|
|
return IterableFibonacci.this.next();
|
|
|
|
|
}
|
2015-05-05 11:20:13 -07:00
|
|
|
|
@Override
|
2015-04-20 15:36:01 -07:00
|
|
|
|
public void remove() { // Not implemented
|
|
|
|
|
throw new UnsupportedOperationException();
|
|
|
|
|
}
|
|
|
|
|
};
|
2015-05-18 23:05:20 -07:00
|
|
|
|
}
|
2015-04-20 15:36:01 -07:00
|
|
|
|
public static void main(String[] args) {
|
|
|
|
|
for(int i : new IterableFibonacci(18))
|
|
|
|
|
System.out.print(i + " ");
|
|
|
|
|
}
|
|
|
|
|
} /* Output:
|
|
|
|
|
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584
|
|
|
|
|
*///:~
|