1 package sharin.unlinq;
2
3 import java.util.Iterator;
4 import java.util.LinkedList;
5 import java.util.NoSuchElementException;
6 import java.util.Queue;
7
8 public abstract class QueuedIterator<T, E, R> implements Iterator<R> {
9
10 private final Iterator<T> iterator;
11
12 private Queue<E> queue = new LinkedList<E>();
13
14 public QueuedIterator(Iterator<T> iterator) {
15 this.iterator = iterator;
16 }
17
18 protected abstract void addElement(Queue<E> queue, T t);
19
20 protected abstract R toResult(E e);
21
22 public boolean hasNext() {
23
24
25 if (queue == null) {
26 return false;
27 }
28
29
30 if (!queue.isEmpty()) {
31 return true;
32 }
33
34 while (iterator.hasNext()) {
35 addElement(queue, iterator.next());
36
37 if (!queue.isEmpty()) {
38 return true;
39 }
40 }
41
42
43 queue = null;
44 return false;
45 }
46
47 public R next() {
48
49
50 if (queue == null) {
51 throw new NoSuchElementException();
52 }
53
54
55 if (queue.isEmpty()) {
56
57 if (!hasNext()) {
58 throw new NoSuchElementException();
59 }
60 }
61
62 return toResult(queue.remove());
63 }
64
65 public void remove() {
66 throw new UnsupportedOperationException();
67 }
68 }