View Javadoc
1   /*
2    * Copyright (C) 2007 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
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   * Note this class is a copy of
28   * {@link com.google.common.collect.AbstractIterator} (for dependency reasons).
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; // temporary pessimism
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  }