通常认为提供Iterator"无限"的实现是不好的做法; 即对hasNext()always(*)的调用返回true的位置?
通常我会说"是",因为调用代码可能表现不正常,但在下面的实现hasNext()中将返回true,除非调用者从List中删除迭代器初始化的所有元素; 即存在终止条件.你认为这是合法用途Iterator吗?它似乎没有违反合同,虽然我认为有人可能认为这是不直观的.
public class CyclicIterator<T> implements Iterator<T> {
private final List<T> l;
private Iterator<T> 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 …Run Code Online (Sandbox Code Playgroud)