Re: Efficiently sequencing a stream of objects
Chris wrote:
Generics, unfortunately, are worthless for performance improvements.
They provide only compile-time type checking. At runtime, all the casts
are still there.
Not all cast are there. Compare your version with "genericified" one
(attached below).
piotr
--
public class MergingIterator<E extends Comparable<? super E>> implements
Iterator<E> {
private PriorityQueue<Carrier> queue = new PriorityQueue<Carrier>();
public void add(Iterator<? extends E> it) {
if (!it.hasNext())
return; // do nothing, do not add
Carrier carrier = new Carrier();
carrier.it = it;
carrier.next = it.next();
queue.offer(carrier);
}
public boolean hasNext() {
return !queue.isEmpty();
}
public E next() {
Carrier carrier = queue.poll();
E next = carrier.next;
// if there's another object to be had from this stream, insert it.
// if not, the queue just gets smaller
if (carrier.it.hasNext()) {
carrier.next = carrier.it.next();
queue.offer(carrier);
}
return next;
}
public void remove() {
throw new UnsupportedOperationException();
}
private class Carrier implements Comparable<Carrier> {
Iterator<? extends E> it;
E next;
public int compareTo(Carrier other) {
return next.compareTo(other.next);
}
}
}