1 /* 2 * Copyright (C) 2007 Google Inc. 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.collect; 18 19 import com.google.common.annotations.GwtCompatible; 20 import static com.google.common.base.Preconditions.checkState; 21 22 import java.util.NoSuchElementException; 23 24 /** 25 * This class provides a skeletal implementation of the {@code Iterator} 26 * interface, to make this interface easier to implement for certain types of 27 * data sources. 28 * 29 * <p>{@code Iterator} requires its implementations to support querying the 30 * end-of-data status without changing the iterator's state, using the {@link 31 * #hasNext} method. But many data sources, such as {@link 32 * java.io.Reader#read()}), do not expose this information; the only way to 33 * discover whether there is any data left is by trying to retrieve it. These 34 * types of data sources are ordinarily difficult to write iterators for. But 35 * using this class, one must implement only the {@link #computeNext} method, 36 * and invoke the {@link #endOfData} method when appropriate. 37 * 38 * <p>Another example is an iterator that skips over null elements in a backing 39 * iterator. This could be implemented as: <pre> {@code 40 * 41 * public static Iterator<String> skipNulls(final Iterator<String> in) { 42 * return new AbstractIterator<String>() { 43 * protected String computeNext() { 44 * while (in.hasNext()) { 45 * String s = in.next(); 46 * if (s != null) { 47 * return s; 48 * } 49 * } 50 * return endOfData(); 51 * } 52 * }; 53 * }}</pre> 54 * 55 * This class supports iterators that include null elements. 56 * 57 * @author Kevin Bourrillion 58 * @since 2010.01.04 <b>stable</b> (imported from Google Collections Library) 59 */ 60 @GwtCompatible 61 public abstract class AbstractIterator<T> extends UnmodifiableIterator<T> { 62 private State state = State.NOT_READY; 63 64 private enum State { 65 /** We have computed the next element and haven't returned it yet. */ 66 READY, 67 68 /** We haven't yet computed or have already returned the element. */ 69 NOT_READY, 70 71 /** We have reached the end of the data and are finished. */ 72 DONE, 73 74 /** We've suffered an exception and are kaput. */ 75 FAILED, 76 } 77 78 private T next; 79 80 /** 81 * Returns the next element. <b>Note:</b> the implementation must call {@link 82 * #endOfData()} when there are no elements left in the iteration. Failure to 83 * do so could result in an infinite loop. 84 * 85 * <p>The initial invocation of {@link #hasNext()} or {@link #next()} calls 86 * this method, as does the first invocation of {@code hasNext} or {@code 87 * next} following each successful call to {@code next}. Once the 88 * implementation either invokes {@code endOfData} or throws an exception, 89 * {@code computeNext} is guaranteed to never be called again. 90 * 91 * <p>If this method throws an exception, it will propagate outward to the 92 * {@code hasNext} or {@code next} invocation that invoked this method. Any 93 * further attempts to use the iterator will result in an {@link 94 * IllegalStateException}. 95 * 96 * <p>The implementation of this method may not invoke the {@code hasNext}, 97 * {@code next}, or {@link #peek()} methods on this instance; if it does, an 98 * {@code IllegalStateException} will result. 99 * 100 * @return the next element if there was one. If {@code endOfData} was called 101 * during execution, the return value will be ignored. 102 * @throws RuntimeException if any unrecoverable error happens. This exception 103 * will propagate outward to the {@code hasNext()}, {@code next()}, or 104 * {@code peek()} invocation that invoked this method. Any further 105 * attempts to use the iterator will result in an 106 * {@link IllegalStateException}. 107 */ 108 protected abstract T computeNext(); 109 110 /** 111 * Implementations of {@code computeNext} <b>must</b> invoke this method when 112 * there are no elements left in the iteration. 113 * 114 * @return {@code null}; a convenience so your {@link #computeNext} 115 * implementation can use the simple statement {@code return endOfData();} 116 */ 117 protected final T endOfData() { 118 state = State.DONE; 119 return null; 120 } 121 122 public final boolean hasNext() { 123 checkState(state != State.FAILED); 124 switch (state) { 125 case DONE: 126 return false; 127 case READY: 128 return true; 129 default: 130 } 131 return tryToComputeNext(); 132 } 133 134 private boolean tryToComputeNext() { 135 state = State.FAILED; // temporary pessimism 136 next = computeNext(); 137 if (state != State.DONE) { 138 state = State.READY; 139 return true; 140 } 141 return false; 142 } 143 144 public final T next() { 145 if (!hasNext()) { 146 throw new NoSuchElementException(); 147 } 148 state = State.NOT_READY; 149 return next; 150 } 151 152 /** 153 * Returns the next element in the iteration without advancing the iteration, 154 * according to the contract of {@link PeekingIterator#peek()}. 155 * 156 * <p>Implementations of {@code AbstractIterator} that wish to expose this 157 * functionality should implement {@code PeekingIterator}. 158 */ 159 public final T peek() { 160 if (!hasNext()) { 161 throw new NoSuchElementException(); 162 } 163 return next; 164 } 165 } 166