View Javadoc

1   package net.sf.composite.util;
2   
3   import java.lang.reflect.Array;
4   import java.util.Iterator;
5   import java.util.NoSuchElementException;
6   
7   /***
8    * An iterator over the contents of an array.  This implementation only allows
9    * an array to be iterated over once, but a reset method could easily be added
10   * to allow for the array to be iterated over multiple times or for another
11   * array to use the same ArrayIterator instance as an iterator for it.
12   * 
13   * @author Matt Sgarlata
14   * @since Dec 5, 2004
15   */
16  public class ArrayIterator implements Iterator {
17  
18  	private int index;
19  	private Object array;
20  	
21  	public ArrayIterator() {
22  		this.index = 0;
23  	}
24  	
25  	public ArrayIterator(Object array) {
26  		this();
27  		setArray(array);
28  	}
29  	
30  	public boolean hasNext() {
31  		if (array == null) {
32  			return false;
33  		}
34  		return index < Array.getLength(array);
35  	}
36  
37  	public Object next() {
38  		if (array == null) {
39  			throw new NoSuchElementException("The array was null, so there are no elements to iterate over");
40  		}
41  		if (index == Array.getLength(array)) {
42  			throw new NoSuchElementException("There are no more elements to iterate over");
43  		}
44  		return Array.get(array, index++);
45  	}
46  
47  	public void remove() {
48  		throw new UnsupportedOperationException();
49  	}
50  
51  	/***
52  	 * @return Returns the array.
53  	 */
54  	public Object getArray() {
55  		return array;
56  	}
57  	/***
58  	 * Sets the array to be iterated over
59  	 * @param array The array to set.
60  	 * @throws IllegalStateException if this method is called after a call has been made to next()
61  	 * @throws IllegalArgumentException if the supplied object is not an array
62  	 */
63  	public void setArray(Object array) {
64  		if (index != 0) {
65  			throw new IllegalStateException("Cannot change the array of an iterator that has already begun traversal");
66  		}
67  		if (array != null && !array.getClass().isArray()) {
68  			throw new IllegalArgumentException("The supplied array argument must be an array type, but '" + array.getClass().getName() + "' is not");
69  		}
70  		this.array = array;
71  	}
72  }