1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.base;
18
19 import static com.google.common.base.Preconditions.checkState;
20
21 import com.google.common.annotations.GwtCompatible;
22
23 import java.util.Iterator;
24 import java.util.NoSuchElementException;
25
26
27
28
29
30 @GwtCompatible
31 abstract class AbstractIterator<T> implements Iterator<T> {
32 private State state = State.NOT_READY;
33
34 protected AbstractIterator() {}
35
36 private enum State {
37 READY, NOT_READY, DONE, FAILED,
38 }
39
40 private T next;
41
42 protected abstract T computeNext();
43
44 protected final T endOfData() {
45 state = State.DONE;
46 return null;
47 }
48
49 @Override
50 public final boolean hasNext() {
51 checkState(state != State.FAILED);
52 switch (state) {
53 case DONE:
54 return false;
55 case READY:
56 return true;
57 default:
58 }
59 return tryToComputeNext();
60 }
61
62 private boolean tryToComputeNext() {
63 state = State.FAILED;
64 next = computeNext();
65 if (state != State.DONE) {
66 state = State.READY;
67 return true;
68 }
69 return false;
70 }
71
72 @Override
73 public final T next() {
74 if (!hasNext()) {
75 throw new NoSuchElementException();
76 }
77 state = State.NOT_READY;
78 T result = next;
79 next = null;
80 return result;
81 }
82
83 @Override public final void remove() {
84 throw new UnsupportedOperationException();
85 }
86 }