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