001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.collections4.iterators;
018
019import java.util.Iterator;
020import java.util.NoSuchElementException;
021import java.util.Objects;
022
023/**
024 * Decorates another iterator to return elements in a specific range.
025 * <p>
026 * The decorated iterator is bounded in the range [offset, offset+max).
027 * The {@code offset} corresponds to the position of the first element to
028 * be returned from the decorated iterator, and {@code max} is the maximum
029 * number of elements to be returned at most.
030 * <p>
031 * In case an offset parameter other than 0 is provided, the decorated
032 * iterator is immediately advanced to this position, skipping all elements
033 * before that position.
034 *
035 * @param <E> the type of elements returned by this iterator.
036 * @since 4.1
037 */
038public class BoundedIterator<E> implements Iterator<E> {
039
040    /** The iterator being decorated. */
041    private final Iterator<? extends E> iterator;
042
043    /** The offset to bound the first element return */
044    private final long offset;
045
046    /** The max number of elements to return */
047    private final long max;
048
049    /** The position of the current element */
050    private long pos;
051
052    /**
053     * Decorates the specified iterator to return at most the given number of elements,
054     * skipping all elements until the iterator reaches the position at {@code offset}.
055     * <p>
056     * The iterator is immediately advanced until it reaches the position at {@code offset},
057     * incurring O(n) time.
058     *
059     * @param iterator  the iterator to be decorated
060     * @param offset  the index of the first element of the decorated iterator to return
061     * @param max  the maximum number of elements of the decorated iterator to return
062     * @throws NullPointerException if iterator is null
063     * @throws IllegalArgumentException if either offset or max is negative
064     */
065    public BoundedIterator(final Iterator<? extends E> iterator, final long offset, final long max) {
066        if (offset < 0) {
067            throw new IllegalArgumentException("Offset parameter must not be negative.");
068        }
069        if (max < 0) {
070            throw new IllegalArgumentException("Max parameter must not be negative.");
071        }
072
073        this.iterator = Objects.requireNonNull(iterator, "iterator");
074        this.offset = offset;
075        this.max = max;
076        pos = 0;
077        init();
078    }
079
080    /**
081     * Checks whether the iterator is still within its bounded range.
082     * @return {@code true} if the iterator is within its bounds, {@code false} otherwise
083     */
084    private boolean checkBounds() {
085        if (pos - offset + 1 > max) {
086            return false;
087        }
088        return true;
089    }
090
091    @Override
092    public boolean hasNext() {
093        if (!checkBounds()) {
094            return false;
095        }
096        return iterator.hasNext();
097    }
098
099    /**
100     * Advances the underlying iterator to the beginning of the bounded range.
101     */
102    private void init() {
103        while (pos < offset && iterator.hasNext()) {
104            iterator.next();
105            pos++;
106        }
107    }
108
109    @Override
110    public E next() {
111        if (!checkBounds()) {
112            throw new NoSuchElementException();
113        }
114        final E next = iterator.next();
115        pos++;
116        return next;
117    }
118
119    /**
120     * {@inheritDoc}
121     * <p>
122     * In case an offset other than 0 was specified, the underlying iterator will be advanced
123     * to this position upon creation. A call to {@link #remove()} will still result in an
124     * {@link IllegalStateException} if no explicit call to {@link #next()} has been made prior
125     * to calling {@link #remove()}.
126     */
127    @Override
128    public void remove() {
129        if (pos <= offset) {
130            throw new IllegalStateException("remove() can not be called before calling next()");
131        }
132        iterator.remove();
133    }
134}