Middle
Implement a CompositeIterator using generics that combines two iterators of the same type.
sobes.tech AI
Answer from AI
Below is an example implementation of CompositeIterator in Java using generics, which combines two iterators of the same type T:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class CompositeIterator<T> implements Iterator<T> {
private final Iterator<T> first;
private final Iterator<T> second;
public CompositeIterator(Iterator<T> first, Iterator<T> second) {
this.first = first;
this.second = second;
}
@Override
public boolean hasNext() {
return first.hasNext() || second.hasNext();
}
@Override
public T next() {
if (first.hasNext()) {
return first.next();
} else if (second.hasNext()) {
return second.next();
} else {
throw new NoSuchElementException();
}
}
@Override
public void remove() {
throw new UnsupportedOperationException("Remove not supported");
}
}
This iterator first iterates over elements from the first iterator, then from the second, combining them into a single stream of elements.