View Javadoc

1   package net.sourceforge.pmd.util;
2   
3   import java.util.Iterator;
4   import java.util.NoSuchElementException;
5   
6   /**
7    * Creates a single compound Iterator from an array of Iterators.
8    * 
9    * @param <T> The type returned by the Iterator.
10   * 
11   * @see Iterator
12   */
13  public class CompoundIterator<T> implements Iterator<T> {
14      private final Iterator<T>[] iterators;
15      private int index;
16  
17      /**
18       * 
19       * @param iterators The iterators use.
20       */
21      public CompoundIterator(Iterator<T>... iterators) {
22  	this.iterators = iterators;
23  	this.index = 0;
24      }
25  
26      /**
27       * {@inheritDoc}
28       */
29      public boolean hasNext() {
30  	return getNextIterator() != null;
31      }
32  
33      /**
34       * {@inheritDoc}
35       */
36      public T next() {
37  	Iterator<T> iterator = getNextIterator();
38  	if (iterator != null) {
39  	    return iterator.next();
40  	} else {
41  	    throw new NoSuchElementException();
42  	}
43      }
44  
45      /**
46       * {@inheritDoc}
47       */
48      public void remove() {
49  	Iterator<T> iterator = getNextIterator();
50  	if (iterator != null) {
51  	    iterator.remove();
52  	} else {
53  	    throw new IllegalStateException();
54  	}
55      }
56  
57      // Get the next iterator with values, returns null if there is no such iterator
58      private Iterator<T> getNextIterator() {
59  	while (index < iterators.length) {
60  	    if (iterators[index].hasNext()) {
61  		return iterators[index];
62  	    } else {
63  		index++;
64  	    }
65  	}
66  	return null;
67      }
68  }