01: /*
02:
03: This software is OSI Certified Open Source Software.
04: OSI Certified is a certification mark of the Open Source Initiative.
05:
06: The license (Mozilla version 1.0) can be read at the MMBase site.
07: See http://www.MMBase.org/license
08:
09: */
10:
11: package org.mmbase.util;
12:
13: import java.util.*;
14:
15: /**
16: * Like org.apache.commons.collections.iterators.IteratorChain, to avoid the dependency....
17: *
18: * @author Michiel Meeuwissen
19: * @since MMBase-1.8
20: * @version $Id: ChainedIterator.java,v 1.4 2007/02/24 21:57:50 nklasens Exp $
21: */
22: public class ChainedIterator<E> implements Iterator<E> {
23:
24: List<Iterator<E>> iterators = new ArrayList<Iterator<E>>();
25: Iterator<Iterator<E>> iteratorIterator = null;
26: Iterator<E> iterator = null;
27:
28: public ChainedIterator() {
29: }
30:
31: public void addIterator(Iterator<E> i) {
32: if (iteratorIterator != null)
33: throw new IllegalStateException();
34: iterators.add(i);
35: }
36:
37: private void setIterator() {
38: while (iteratorIterator.hasNext() && iterator == null) {
39: iterator = iteratorIterator.next();
40: if (!iterator.hasNext())
41: iterator = null;
42: }
43: }
44:
45: private void start() {
46: if (iteratorIterator == null) {
47: iteratorIterator = iterators.iterator();
48: setIterator();
49: }
50: }
51:
52: public boolean hasNext() {
53: start();
54: return (iterator != null && iterator.hasNext());
55:
56: }
57:
58: public E next() {
59: start();
60: if (iterator == null)
61: throw new NoSuchElementException();
62: E res = iterator.next();
63: if (!iterator.hasNext()) {
64: iterator = null;
65: setIterator();
66: }
67: return res;
68:
69: }
70:
71: public void remove() {
72: throw new UnsupportedOperationException();
73: }
74:
75: /**
76: * Just testing
77: */
78: public static void main(String argv[]) {
79: ChainedIterator<String> it = new ChainedIterator<String>();
80: List<String> o = new ArrayList<String>();
81: List<String> a = new ArrayList<String>();
82: a.add("a");
83: a.add("b");
84: List<String> b = new ArrayList<String>();
85: List<String> c = new ArrayList<String>();
86: c.add("c");
87: c.add("d");
88: List<String> d = new ArrayList<String>();
89: it.addIterator(o.iterator());
90: it.addIterator(a.iterator());
91: it.addIterator(b.iterator());
92: it.addIterator(c.iterator());
93: it.addIterator(d.iterator());
94: while (it.hasNext()) {
95: System.out.println("" + it.next());
96: }
97: }
98:
99: }
|