KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hibernate > util > JoinedIterator


1 //$Id: JoinedIterator.java,v 1.2 2004/06/28 23:58:08 epbernard Exp $
2
package org.hibernate.util;
3
4 import java.util.Iterator JavaDoc;
5 import java.util.List JavaDoc;
6
7 /**
8  * An JoinedIterator is an Iterator that wraps a number of Iterators.
9  *
10  * This class makes multiple iterators look like one to the caller.
11  * When any method from the Iterator interface is called, the JoinedIterator
12  * will delegate to a single underlying Iterator. The JoinedIterator will
13  * invoke the Iterators in sequence until all Iterators are exhausted.
14  *
15  */

16 public class JoinedIterator implements Iterator JavaDoc {
17
18     private static final Iterator JavaDoc[] ITERATORS = {};
19
20     // wrapped iterators
21
private Iterator JavaDoc[] iterators;
22
23     // index of current iterator in the wrapped iterators array
24
private int currentIteratorIndex;
25
26     // the current iterator
27
private Iterator JavaDoc currentIterator;
28
29     // the last used iterator
30
private Iterator JavaDoc lastUsedIterator;
31
32     public JoinedIterator(List JavaDoc iterators) {
33         this( (Iterator JavaDoc[]) iterators.toArray(ITERATORS) );
34     }
35
36     public JoinedIterator(Iterator JavaDoc[] iterators) {
37         if( iterators==null )
38             throw new NullPointerException JavaDoc("Unexpected NULL iterators argument");
39         this.iterators = iterators;
40     }
41
42     public JoinedIterator(Iterator JavaDoc first, Iterator JavaDoc second) {
43         this( new Iterator JavaDoc[] { first, second } );
44     }
45
46     public boolean hasNext() {
47         updateCurrentIterator();
48         return currentIterator.hasNext();
49     }
50
51     public Object JavaDoc next() {
52         updateCurrentIterator();
53         return currentIterator.next();
54     }
55
56     public void remove() {
57         updateCurrentIterator();
58         lastUsedIterator.remove();
59     }
60
61
62     // call this before any Iterator method to make sure that the current Iterator
63
// is not exhausted
64
protected void updateCurrentIterator() {
65
66         if (currentIterator == null) {
67             if( iterators.length==0 ) {
68                 currentIterator = EmptyIterator.INSTANCE;
69             }
70             else {
71                 currentIterator = iterators[0];
72             }
73             // set last used iterator here, in case the user calls remove
74
// before calling hasNext() or next() (although they shouldn't)
75
lastUsedIterator = currentIterator;
76         }
77
78         while (! currentIterator.hasNext() && currentIteratorIndex < iterators.length - 1) {
79             currentIteratorIndex++;
80             currentIterator = iterators[currentIteratorIndex];
81         }
82     }
83
84 }
85
Popular Tags