/** * Closes every CloseableIterator in this MergingIterator. After calling, calls to hasNext() will * always return false. */ @Override public void close() { for (final ComparableIterator iterator : this.queue) { iterator.close(); this.queue.remove(iterator); } }
@Override public int compareTo(final ComparableIterator that) { if (comparator.getClass() != comparator.getClass()) { throw new IllegalStateException( "Can't compare two ComparableIterators that have different orderings."); } return comparator.compare(this.peek(), that.peek()); }
/** @see java.util.Iterator<T>.next */ @Override public T next() { if (!this.hasNext()) throw new NoSuchElementException(); final ComparableIterator recordIterator = this.queue.poll(); // Assumes the iterator is closed & removed from the queue before recordIterator.hasNext() == // false final T next = recordIterator.next(); // I don't like having to test for null here -- it's really only null before the first call // to next() -- but I don't see any other way if (this.lastReturned != null && this.comparator.compare(lastReturned, next) > 0) { throw new IllegalStateException( "The elements of the input Iterators are not sorted according to the comparator " + this.comparator.getClass().getName()); } addIfNotEmpty(recordIterator); this.lastReturned = next; return next; }
private void addIfNotEmpty(final ComparableIterator iterator) { if (iterator.hasNext()) queue.offer(iterator); else iterator.close(); }