01: //$Id: JoinedIterator.java 3973 2004-06-28 23:58:08Z epbernard $
02: package org.hibernate.util;
03:
04: import java.util.Iterator;
05: import java.util.List;
06:
07: /**
08: * An JoinedIterator is an Iterator that wraps a number of Iterators.
09: *
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 {
17:
18: private static final Iterator[] ITERATORS = {};
19:
20: // wrapped iterators
21: private Iterator[] iterators;
22:
23: // index of current iterator in the wrapped iterators array
24: private int currentIteratorIndex;
25:
26: // the current iterator
27: private Iterator currentIterator;
28:
29: // the last used iterator
30: private Iterator lastUsedIterator;
31:
32: public JoinedIterator(List iterators) {
33: this ((Iterator[]) iterators.toArray(ITERATORS));
34: }
35:
36: public JoinedIterator(Iterator[] iterators) {
37: if (iterators == null)
38: throw new NullPointerException(
39: "Unexpected NULL iterators argument");
40: this .iterators = iterators;
41: }
42:
43: public JoinedIterator(Iterator first, Iterator second) {
44: this (new Iterator[] { first, second });
45: }
46:
47: public boolean hasNext() {
48: updateCurrentIterator();
49: return currentIterator.hasNext();
50: }
51:
52: public Object next() {
53: updateCurrentIterator();
54: return currentIterator.next();
55: }
56:
57: public void remove() {
58: updateCurrentIterator();
59: lastUsedIterator.remove();
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: } else {
70: currentIterator = iterators[0];
71: }
72: // set last used iterator here, in case the user calls remove
73: // before calling hasNext() or next() (although they shouldn't)
74: lastUsedIterator = currentIterator;
75: }
76:
77: while (!currentIterator.hasNext()
78: && currentIteratorIndex < iterators.length - 1) {
79: currentIteratorIndex++;
80: currentIterator = iterators[currentIteratorIndex];
81: }
82: }
83:
84: }
|