-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathCompositeIterator.java
52 lines (45 loc) · 1.38 KB
/
CompositeIterator.java
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
46
47
48
49
50
51
52
package by.andd3dfx.iterators;
import java.util.Iterator;
/**
* <pre>
* Реализовать методы next(), hasNext(), remove() у составного итератора, содержащего 2 обычных итератора внутри себя:
*
* class CompositeIterator<Integer> {
* Iterator<Integer> a;
* Iterator<Integer> b;
* }
* </pre>
*
* @see <a href="https://youtu.be/8V_t64QLN7Q">Video solution</a>
*/
public class CompositeIterator<T> implements Iterator<T> {
private final Iterator<T> a;
private final Iterator<T> b;
private Iterator<T> currentIterator;
public CompositeIterator(Iterator<T> a, Iterator<T> b) {
this.a = a;
this.b = b;
currentIterator = a;
}
@Override
public boolean hasNext() {
if (currentIterator == a && !currentIterator.hasNext()) {
currentIterator = b;
}
return currentIterator.hasNext();
}
@Override
public T next() {
if (currentIterator == a && !currentIterator.hasNext()) {
currentIterator = b;
}
return currentIterator.next();
}
@Override
public void remove() {
if (currentIterator == a && !currentIterator.hasNext()) {
currentIterator = b;
}
currentIterator.remove();
}
}