001 /*
002 * Copyright (C) 2007 Google Inc.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017 package com.google.common.collect;
018
019 import static com.google.common.base.Preconditions.checkState;
020
021 import com.google.common.annotations.GwtCompatible;
022
023 import java.util.NoSuchElementException;
024
025 /**
026 * This class provides a skeletal implementation of the {@code Iterator}
027 * interface, to make this interface easier to implement for certain types of
028 * data sources.
029 *
030 * <p>{@code Iterator} requires its implementations to support querying the
031 * end-of-data status without changing the iterator's state, using the {@link
032 * #hasNext} method. But many data sources, such as {@link
033 * java.io.Reader#read()}), do not expose this information; the only way to
034 * discover whether there is any data left is by trying to retrieve it. These
035 * types of data sources are ordinarily difficult to write iterators for. But
036 * using this class, one must implement only the {@link #computeNext} method,
037 * and invoke the {@link #endOfData} method when appropriate.
038 *
039 * <p>Another example is an iterator that skips over null elements in a backing
040 * iterator. This could be implemented as: <pre> {@code
041 *
042 * public static Iterator<String> skipNulls(final Iterator<String> in) {
043 * return new AbstractIterator<String>() {
044 * protected String computeNext() {
045 * while (in.hasNext()) {
046 * String s = in.next();
047 * if (s != null) {
048 * return s;
049 * }
050 * }
051 * return endOfData();
052 * }
053 * };
054 * }}</pre>
055 *
056 * This class supports iterators that include null elements.
057 *
058 * @author Kevin Bourrillion
059 * @since 2 (imported from Google Collections Library)
060 */
061 @GwtCompatible
062 public abstract class AbstractIterator<T> extends UnmodifiableIterator<T> {
063 private State state = State.NOT_READY;
064
065 private enum State {
066 /** We have computed the next element and haven't returned it yet. */
067 READY,
068
069 /** We haven't yet computed or have already returned the element. */
070 NOT_READY,
071
072 /** We have reached the end of the data and are finished. */
073 DONE,
074
075 /** We've suffered an exception and are kaput. */
076 FAILED,
077 }
078
079 private T next;
080
081 /**
082 * Returns the next element. <b>Note:</b> the implementation must call {@link
083 * #endOfData()} when there are no elements left in the iteration. Failure to
084 * do so could result in an infinite loop.
085 *
086 * <p>The initial invocation of {@link #hasNext()} or {@link #next()} calls
087 * this method, as does the first invocation of {@code hasNext} or {@code
088 * next} following each successful call to {@code next}. Once the
089 * implementation either invokes {@code endOfData} or throws an exception,
090 * {@code computeNext} is guaranteed to never be called again.
091 *
092 * <p>If this method throws an exception, it will propagate outward to the
093 * {@code hasNext} or {@code next} invocation that invoked this method. Any
094 * further attempts to use the iterator will result in an {@link
095 * IllegalStateException}.
096 *
097 * <p>The implementation of this method may not invoke the {@code hasNext},
098 * {@code next}, or {@link #peek()} methods on this instance; if it does, an
099 * {@code IllegalStateException} will result.
100 *
101 * @return the next element if there was one. If {@code endOfData} was called
102 * during execution, the return value will be ignored.
103 * @throws RuntimeException if any unrecoverable error happens. This exception
104 * will propagate outward to the {@code hasNext()}, {@code next()}, or
105 * {@code peek()} invocation that invoked this method. Any further
106 * attempts to use the iterator will result in an
107 * {@link IllegalStateException}.
108 */
109 protected abstract T computeNext();
110
111 /**
112 * Implementations of {@code computeNext} <b>must</b> invoke this method when
113 * there are no elements left in the iteration.
114 *
115 * @return {@code null}; a convenience so your {@link #computeNext}
116 * implementation can use the simple statement {@code return endOfData();}
117 */
118 protected final T endOfData() {
119 state = State.DONE;
120 return null;
121 }
122
123 public final boolean hasNext() {
124 checkState(state != State.FAILED);
125 switch (state) {
126 case DONE:
127 return false;
128 case READY:
129 return true;
130 default:
131 }
132 return tryToComputeNext();
133 }
134
135 private boolean tryToComputeNext() {
136 state = State.FAILED; // temporary pessimism
137 next = computeNext();
138 if (state != State.DONE) {
139 state = State.READY;
140 return true;
141 }
142 return false;
143 }
144
145 public final T next() {
146 if (!hasNext()) {
147 throw new NoSuchElementException();
148 }
149 state = State.NOT_READY;
150 return next;
151 }
152
153 /**
154 * Returns the next element in the iteration without advancing the iteration,
155 * according to the contract of {@link PeekingIterator#peek()}.
156 *
157 * <p>Implementations of {@code AbstractIterator} that wish to expose this
158 * functionality should implement {@code PeekingIterator}.
159 */
160 public final T peek() {
161 if (!hasNext()) {
162 throw new NoSuchElementException();
163 }
164 return next;
165 }
166 }