1 /* 2 * Copyright (C) 2010 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.collect; 18 19 import com.google.common.annotations.GwtCompatible; 20 import java.util.NoSuchElementException; 21 import javax.annotation.CheckForNull; 22 23 /** 24 * This class provides a skeletal implementation of the {@code Iterator} interface for sequences 25 * whose next element can always be derived from the previous element. Null elements are not 26 * supported, nor is the {@link #remove()} method. 27 * 28 * <p>Example: 29 * 30 * <pre>{@code 31 * Iterator<Integer> powersOfTwo = 32 * new AbstractSequentialIterator<Integer>(1) { 33 * protected Integer computeNext(Integer previous) { 34 * return (previous == 1 << 30) ? null : previous * 2; 35 * } 36 * }; 37 * }</pre> 38 * 39 * @author Chris Povirk 40 * @since 12.0 (in Guava as {@code AbstractLinkedIterator} since 8.0) 41 */ 42 @GwtCompatible 43 @ElementTypesAreNonnullByDefault 44 public abstract class AbstractSequentialIterator<T> extends UnmodifiableIterator<T> { 45 @CheckForNull private T nextOrNull; 46 47 /** 48 * Creates a new iterator with the given first element, or, if {@code firstOrNull} is null, 49 * creates a new empty iterator. 50 */ AbstractSequentialIterator(@heckForNull T firstOrNull)51 protected AbstractSequentialIterator(@CheckForNull T firstOrNull) { 52 this.nextOrNull = firstOrNull; 53 } 54 55 /** 56 * Returns the element that follows {@code previous}, or returns {@code null} if no elements 57 * remain. This method is invoked during each call to {@link #next()} in order to compute the 58 * result of a <i>future</i> call to {@code next()}. 59 */ 60 @CheckForNull computeNext(T previous)61 protected abstract T computeNext(T previous); 62 63 @Override hasNext()64 public final boolean hasNext() { 65 return nextOrNull != null; 66 } 67 68 @Override next()69 public final T next() { 70 if (nextOrNull == null) { 71 throw new NoSuchElementException(); 72 } 73 T oldNext = nextOrNull; 74 nextOrNull = computeNext(oldNext); 75 return oldNext; 76 } 77 } 78