01: /**
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */package org.apache.solr.util;
17:
18: import java.util.ArrayList;
19: import java.util.Iterator;
20: import java.util.List;
21:
22: /** Chain several Iterators, so that this iterates
23: * over all of them in sequence.
24: */
25:
26: public class IteratorChain<E> implements Iterator<E> {
27:
28: private final List<Iterator<E>> iterators = new ArrayList<Iterator<E>>();
29: private Iterator<Iterator<E>> itit;
30: private Iterator<E> current;
31:
32: public void addIterator(Iterator<E> it) {
33: if (itit != null)
34: throw new RuntimeException(
35: "all Iterators must be added before calling hasNext()");
36: iterators.add(it);
37: }
38:
39: public boolean hasNext() {
40: if (itit == null)
41: itit = iterators.iterator();
42: return recursiveHasNext();
43: }
44:
45: /** test if current iterator hasNext(), and if not try the next
46: * one in sequence, recursively
47: */
48: private boolean recursiveHasNext() {
49: // return false if we have no more iterators
50: if (current == null) {
51: if (itit.hasNext()) {
52: current = itit.next();
53: } else {
54: return false;
55: }
56: }
57:
58: boolean result = current.hasNext();
59: if (!result) {
60: current = null;
61: result = recursiveHasNext();
62: }
63:
64: return result;
65: }
66:
67: /** hasNext() must ALWAYS be called before calling this
68: * otherwise it's a bit hard to keep track of what's happening
69: */
70: public E next() {
71: if (current == null) {
72: throw new RuntimeException(
73: "For an IteratorChain, hasNext() MUST be called before calling next()");
74: }
75: return current.next();
76: }
77:
78: public void remove() {
79: // we just need this class
80: // to iterate in readonly mode
81: throw new UnsupportedOperationException();
82: }
83:
84: }
|