    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.lang.reflect.Array;
    020import java.util.NoSuchElementException;
    021
    022import org.apache.commons.collections4.ResettableIterator;
    023
    024/**
    025 * Implements an {@link java.util.Iterator Iterator} over any array.
    026 * <p>
    027 * The array can be either an array of object or of primitives. If you know
    028 * that you have an object array, the
    029 * {@link org.apache.commons.collections4.iterators.ObjectArrayIterator ObjectArrayIterator}
    030 * class is a better choice, as it will perform better.
    031 * <p>
    032 * The iterator implements a {@link #reset} method, allowing the reset of
    033 * the iterator back to the start if required.
    034 *
    035 * @param <E> the type of elements returned by this iterator.
    036 * @since 1.0
    037 */
    038public class ArrayIterator<E> implements ResettableIterator<E> {
    039
    040    /** The array to iterate over */
    041    final Object array;
    042    /** The start index to loop from */
    043    final int startIndex;
    044    /** The end index to loop to */
    045    final int endIndex;
    046    /** The current iterator index */
    047    int index;
    048
    049    /**
    050     * Constructs an ArrayIterator that will iterate over the values in the
    051     * specified array.
    052     *
    053     * @param array the array to iterate over.
    054     * @throws IllegalArgumentException if {@code array} is not an array.
    055     * @throws NullPointerException if {@code array} is {@code null}
    056     */
    057    public ArrayIterator(final Object array) {
    058        this(array, 0);
    059    }
    060
    061    /**
    062     * Constructs an ArrayIterator that will iterate over the values in the
    063     * specified array from a specific start index.
    064     *
    065     * @param array  the array to iterate over.
    066     * @param startIndex  the index to start iterating at.
    067     * @throws IllegalArgumentException if {@code array} is not an array.
    068     * @throws NullPointerException if {@code array} is {@code null}
    069     * @throws IndexOutOfBoundsException if the index is invalid
    070     */
    071    public ArrayIterator(final Object array, final int startIndex) {
    072        this(array, startIndex, Array.getLength(array));
    073    }
    074
    075    /**
    076     * Constructs an ArrayIterator that will iterate over a range of values
    077     * in the specified array.
    078     *
    079     * @param array  the array to iterate over.
    080     * @param startIndex  the index to start iterating at.
    081     * @param endIndex  the index to finish iterating at.
    082     * @throws IllegalArgumentException if {@code array} is not an array.
    083     * @throws NullPointerException if {@code array} is {@code null}
    084     * @throws IndexOutOfBoundsException if either index is invalid
    085     */
    086    public ArrayIterator(final Object array, final int startIndex, final int endIndex) {
    087        this.array = array;
    088        this.startIndex = startIndex;
    089        this.endIndex = endIndex;
    090        this.index = startIndex;
    091
    092        final int len = Array.getLength(array);
    093        checkBound(startIndex, len, "start");
    094        checkBound(endIndex, len, "end");
    095        if (endIndex < startIndex) {
    096            throw new IllegalArgumentException("End index must not be less than start index.");
    097        }
    098    }
    099
    100    /**
    101     * Checks whether the index is valid or not.
    102     *
    103     * @param bound  the index to check
    104     * @param len  the length of the array
    105     * @param type  the index type (for error messages)
    106     * @throws IndexOutOfBoundsException if the index is invalid
    107     */
    108    protected void checkBound(final int bound, final int len, final String type ) {
    109        if (bound > len) {
    110            throw new ArrayIndexOutOfBoundsException(
    111              "Attempt to make an ArrayIterator that " + type +
    112              "s beyond the end of the array. "
    113            );
    114        }
    115        if (bound < 0) {
    116            throw new ArrayIndexOutOfBoundsException(
    117              "Attempt to make an ArrayIterator that " + type +
    118              "s before the start of the array. "
    119            );
    120        }
    121    }
    122
    123    // Properties
    124    /**
    125     * Gets the array that this iterator is iterating over.
    126     *
    127     * @return the array this iterator iterates over.
    128     */
    129    public Object getArray() {
    130        return array;
    131    }
    132
    133    /**
    134     * Gets the end index to loop to.
    135     *
    136     * @return the end index
    137     * @since 4.0
    138     */
    139    public int getEndIndex() {
    140        return this.endIndex;
    141    }
    142
    143    /**
    144     * Gets the start index to loop from.
    145     *
    146     * @return the start index
    147     * @since 4.0
    148     */
    149    public int getStartIndex() {
    150        return this.startIndex;
    151    }
    152
    153    // Iterator interface
    154    /**
    155     * Returns true if there are more elements to return from the array.
    156     *
    157     * @return true if there is a next element to return
    158     */
    159    @Override
    160    public boolean hasNext() {
    161        return index < endIndex;
    162    }
    163
    164    /**
    165     * Returns the next element in the array.
    166     *
    167     * @return the next element in the array
    168     * @throws NoSuchElementException if all the elements in the array
    169     *  have already been returned
    170     */
    171    @Override
    172    @SuppressWarnings("unchecked")
    173    public E next() {
    174        if (!hasNext()) {
    175            throw new NoSuchElementException();
    176        }
    177        return (E) Array.get(array, index++);
    178    }
    179
    180    /**
    181     * Throws {@link UnsupportedOperationException}.
    182     *
    183     * @throws UnsupportedOperationException always
    184     */
    185    @Override
    186    public void remove() {
    187        throw new UnsupportedOperationException("remove() method is not supported");
    188    }
    189
    190    /**
    191     * Resets the iterator back to the start index.
    192     */
    193    @Override
    194    public void reset() {
    195        this.index = this.startIndex;
    196    }
    197
    198}