Response to the critique for my last post and OneElementIterator
I’ve wrote an update to the post where someone suggested in a trackback to use the JDK for an one element iterator.
I got interested in aa OneElementIterator, which optimized - not sure how fast try is - could look like this:
public class OneElementIterator[T] implements Iterator[T] {
private T element;
public OneElementIterator(T element) {
this.element = element;
}
public boolean hasNext() {
return element != null;
}
public T next() {
try {
return element;
} finally {
element = null;
}
}
Faster and shorter ideas?
Update: Remove got lost during cut & paste:
public void remove() {
// not supported, throw exception
throw new UnsupportedOperationException("Remove not supported in OneElementIterator");
}
And as Eugene noted next() should throw NoSuchElementException .
Much faster to avoid the try (which as you implied, can be quite slow) and instead use a local temporary:
public T next() { T e = element; element = null; return e; }It’s not concurrency safe, but then, neither is yours. :-)
August 8th, 2008