-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiCollection.java
More file actions
45 lines (35 loc) · 1.11 KB
/
MultiCollection.java
File metadata and controls
45 lines (35 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class MultiCollection<E> implements Iterable<E> {
private final Collection<E>[] sources;
public MultiCollection(Collection<E>... sources) {
this.sources = sources;
}
@Override
public Iterator<E> iterator() {
return new MultiCollectionIterator();
}
private class MultiCollectionIterator implements Iterator<E> {
private int iteratorIndex;
private Iterator<E> currentIterator;
@Override
public boolean hasNext() {
while ((currentIterator == null || !currentIterator.hasNext()) && iteratorIndex < sources.length) {
currentIterator = sources[iteratorIndex].iterator();
iteratorIndex++;
}
return currentIterator != null && currentIterator.hasNext();
}
@Override
public E next() {
if (!hasNext()) throw new NoSuchElementException();
return currentIterator.next();
}
@Override
public void remove() {
if (currentIterator == null) throw new IllegalStateException();
currentIterator.remove();
}
}
}