反復子の実装を列挙子のインタフェイスで扱う #5

#3の使用例では結局Collectionに対するEnumerationを得ていたのであまりありがたみがない気が。
Iterable由来でない(当然Collection由来でない)Iteratorを与えてみる。

import java.util.Enumeration;
import java.util.Iterator;
...snip
        for (
            Enumeration<Integer> e = enumeration(new Iterator<Integer>() {
                private static final int N = 60;
                private int divisor = 0;
                public boolean hasNext() {
                    return divisor < N;
                }
                public Integer next() {
                    if (! hasNext()) throw new java.util.NoSuchElementException();
                    while (N % ++divisor != 0) ;
                    return divisor;
                }
                public void remove() {
                    throw new UnsupportedOperationException();
                }
            });
            e.hasMoreElements();
        ) {
            System.out.println(e.nextElement());
        }
...snip

実行すると、

1
2
3
4
5
6
10
12
15
20
30
60

N=60の全ての約数を列挙するEnumerationが返されている。