001/*
002 * Copyright (C) 2010 The Guava Authors
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
017package com.google.common.collect;
018
019import com.google.common.annotations.GwtCompatible;
020import java.util.NoSuchElementException;
021import org.checkerframework.checker.nullness.qual.Nullable;
022
023/**
024 * This class provides a skeletal implementation of the {@code Iterator} interface for sequences
025 * whose next element can always be derived from the previous element. Null elements are not
026 * supported, nor is the {@link #remove()} method.
027 *
028 * <p>Example:
029 *
030 * <pre>{@code
031 * Iterator<Integer> powersOfTwo =
032 *     new AbstractSequentialIterator<Integer>(1) {
033 *       protected Integer computeNext(Integer previous) {
034 *         return (previous == 1 << 30) ? null : previous * 2;
035 *       }
036 *     };
037 * }</pre>
038 *
039 * @author Chris Povirk
040 * @since 12.0 (in Guava as {@code AbstractLinkedIterator} since 8.0)
041 */
042@GwtCompatible
043public abstract class AbstractSequentialIterator<T> extends UnmodifiableIterator<T> {
044  private @Nullable T nextOrNull;
045
046  /**
047   * Creates a new iterator with the given first element, or, if {@code firstOrNull} is null,
048   * creates a new empty iterator.
049   */
050  protected AbstractSequentialIterator(@Nullable T firstOrNull) {
051    this.nextOrNull = firstOrNull;
052  }
053
054  /**
055   * Returns the element that follows {@code previous}, or returns {@code null} if no elements
056   * remain. This method is invoked during each call to {@link #next()} in order to compute the
057   * result of a <i>future</i> call to {@code next()}.
058   */
059  protected abstract @Nullable T computeNext(T previous);
060
061  @Override
062  public final boolean hasNext() {
063    return nextOrNull != null;
064  }
065
066  @Override
067  public final T next() {
068    if (nextOrNull == null) {
069      throw new NoSuchElementException();
070    }
071    T oldNext = nextOrNull;
072    nextOrNull = computeNext(oldNext);
073    return oldNext;
074  }
075}