KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > binding > collection > CompositeIterator


1 /*
2  * Copyright 2002-2006 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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 JavaDoc;
19 import java.util.LinkedList JavaDoc;
20 import java.util.List JavaDoc;
21 import java.util.NoSuchElementException JavaDoc;
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 JavaDoc {
33
34     private List JavaDoc iterators = new LinkedList JavaDoc();
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 JavaDoc iterator) {
48         Assert.state(!inUse, "You can no longer add iterator to a composite iterator that's already in use");
49         if (iterators.contains(iterator)) {
50             throw new IllegalArgumentException JavaDoc("You cannot add the same iterator twice");
51         }
52         iterators.add(iterator);
53     }
54
55     public boolean hasNext() {
56         inUse = true;
57         for (Iterator JavaDoc it = iterators.iterator(); it.hasNext(); ) {
58             if (((Iterator JavaDoc)it.next()).hasNext()) {
59                 return true;
60             }
61         }
62         return false;
63     }
64
65     public Object JavaDoc next() {
66         inUse = true;
67         for (Iterator JavaDoc it = iterators.iterator(); it.hasNext(); ) {
68             Iterator JavaDoc iterator = (Iterator JavaDoc)it.next();
69             if (iterator.hasNext()) {
70                 return iterator.next();
71             }
72         }
73         throw new NoSuchElementException JavaDoc("Exhaused all iterators");
74     }
75
76     public void remove() {
77         throw new UnsupportedOperationException JavaDoc("Remove is not supported");
78     }
79 }
Popular Tags