Is an "infinite" iterator bad design?
Posted
by Adamski
on Stack Overflow
See other posts from Stack Overflow
or by Adamski
Published on 2010-04-12T14:00:35Z
Indexed on
2010/04/12
14:02 UTC
Read the original article
Hit count: 391
Is it generally considered bad practice to provide Iterator
implementations that are "infinite"; i.e. where calls to hasNext()
always(*) return true?
Typically I'd say "yes" because the calling code could behave erratically, but in the below implementation hasNext()
will return true unless the caller removes all elements from the List that the iterator was initialised with; i.e. there is a termination condition. Do you think this is a legitimate use of Iterator
? It doesn't seem to violate the contract although I suppose one could argue it's unintuitive.
public class CyclicIterator<T> implements Iterator<T> {
private final List<T> l;
private Iterator it;
public CyclicIterator<T>(List<T> l) {
this.l = l;
this.it = l.iterator();
}
public boolean hasNext() {
return !l.isEmpty();
}
public T next() {
T ret;
if (!hasNext()) {
throw new NoSuchElementException();
} else if (it.hasNext()) {
ret = it.next();
} else {
it = l.iterator();
ret = it.next();
}
return ret;
}
public void remove() {
it.remove();
}
}
© Stack Overflow or respective owner