Java 如何使用迭代器返回特定元素
我有这种迭代器。但我只想在next()方法中返回特定的元素。在我的例子中,我想返回Java 如何使用迭代器返回特定元素,java,Java,我有这种迭代器。但我只想在next()方法中返回特定的元素。在我的例子中,我想返回bagchoffee @Override public Iterator<E> iterator() { return new Iterator<E>(){ private Node<E> current = head; @Override public boolean hasNe
bagchoffee
@Override
public Iterator<E> iterator() {
return new Iterator<E>(){
private Node<E> current = head;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public E next() {
Coffee value = null;
if (!hasNext()) throw new NoSuchElementException();
if(!(current.value instanceof BagCoffee)) {
if(!hasNext()) {
current = current.next;
return next();
} else {
//Stop executing method?
}
} else {
value = current.value;
current = current.next;
}
return (E) value;
}
};
}
问题是,如果接下来没有元素,我就无法停止该方法
if(!hasNext()) {
current = current.next;
return next();
} else {
//Stop executing method
}
使迭代器返回特定元素并停止方法运行的正确方法是什么?主要问题是您没有正确管理迭代器的状态:
current
的值不应包含除BagCoffee
之外的任何内容。
如果是这样,您就不能保证遵守hasNext()
contract方法,因为它可以返回true
,即使下一步没有可用的BagCoffee
因此,您应该通过以下方式确保在对象生命周期的两个不同时间此状态的正确性:
的第一个值
,使其为或空值
的下一个值
,使其为或空值
if(!hasNext()) {
current = current.next;
return next();
} else {
//Stop executing method
}