01: /*
02: * Copyright 2004-2007 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package org.springframework.binding.collection;
17:
18: import java.util.Iterator;
19: import java.util.LinkedList;
20: import java.util.List;
21: import java.util.NoSuchElementException;
22:
23: import org.springframework.util.Assert;
24:
25: /**
26: * Iterator that combines multiple other iterators. This is a simple implementation
27: * that just maintains a list of iterators which are invoked in sequence untill
28: * all iterators are exhausted.
29: *
30: * @author Erwin Vervaet
31: */
32: public class CompositeIterator implements Iterator {
33:
34: private List iterators = new LinkedList();
35:
36: private boolean inUse = false;
37:
38: /**
39: * Create a new composite iterator. Add iterators using the {@link #add(Iterator)} method.
40: */
41: public CompositeIterator() {
42: }
43:
44: /**
45: * Add given iterator to this composite.
46: */
47: public void add(Iterator iterator) {
48: Assert
49: .state(!inUse,
50: "You can no longer add iterator to a composite iterator that's already in use");
51: if (iterators.contains(iterator)) {
52: throw new IllegalArgumentException(
53: "You cannot add the same iterator twice");
54: }
55: iterators.add(iterator);
56: }
57:
58: public boolean hasNext() {
59: inUse = true;
60: for (Iterator it = iterators.iterator(); it.hasNext();) {
61: if (((Iterator) it.next()).hasNext()) {
62: return true;
63: }
64: }
65: return false;
66: }
67:
68: public Object next() {
69: inUse = true;
70: for (Iterator it = iterators.iterator(); it.hasNext();) {
71: Iterator iterator = (Iterator) it.next();
72: if (iterator.hasNext()) {
73: return iterator.next();
74: }
75: }
76: throw new NoSuchElementException("Exhaused all iterators");
77: }
78:
79: public void remove() {
80: throw new UnsupportedOperationException(
81: "Remove is not supported");
82: }
83: }
|