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