/** * Decorates the specified iterator to return at most the given number * of elements, skipping all elements until the iterator reaches the * position at {@code offset}. * <p> * The iterator is immediately advanced until it reaches the position at * {@code offset}, incurring O(n) time. * * @param <E> the element type * @param iterator the iterator to decorate * @param offset the index of the first element of the decorated iterator to return * @param max the maximum number of elements returned by this iterator * @return a new bounded iterator * @throws NullPointerException if the iterator is null * @throws IllegalArgumentException if either offset or max is negative * @since 4.1 */ public static <E> BoundedIterator<E> boundedIterator(final Iterator<? extends E> iterator, final long offset, final long max) { return new BoundedIterator<>(iterator, offset, max); }
@Override public boolean hasNext() { if (!checkBounds()) { return false; } return iterator.hasNext(); }
/** * Decorates the specified iterator to return at most the given number of elements, * skipping all elements until the iterator reaches the position at {@code offset}. * <p> * The iterator is immediately advanced until it reaches the position at {@code offset}, * incurring O(n) time. * * @param iterator the iterator to be decorated * @param offset the index of the first element of the decorated iterator to return * @param max the maximum number of elements of the decorated iterator to return * @throws NullPointerException if iterator is null * @throws IllegalArgumentException if either offset or max is negative */ public BoundedIterator(final Iterator<? extends E> iterator, final long offset, final long max) { if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } if (offset < 0) { throw new IllegalArgumentException("Offset parameter must not be negative."); } if (max < 0) { throw new IllegalArgumentException("Max parameter must not be negative."); } this.iterator = iterator; this.offset = offset; this.max = max; pos = 0; init(); }
@Override public E next() { if (!checkBounds()) { throw new NoSuchElementException(); } final E next = iterator.next(); pos++; return next; }