Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用迭代器返回特定元素_Java - Fatal编程技术网

Java 如何使用迭代器返回特定元素

Java 如何使用迭代器返回特定元素,java,Java,我有这种迭代器。但我只想在next()方法中返回特定的元素。在我的例子中,我想返回bagchoffee @Override public Iterator<E> iterator() { return new Iterator<E>(){ private Node<E> current = head; @Override public boolean hasNe

我有这种迭代器。但我只想在next()方法中返回特定的元素。在我的例子中,我想返回
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

因此,您应该通过以下方式确保在对象生命周期的两个不同时间此状态的正确性:

  • 正确计算当前
    的第一个值
    ,使其为
    或空值
  • 正确计算当前
    的下一个值
    ,使其为
    或空值
  • 然后,您最终可以重构以避免重复代码。

    使hasNext()方法检查当前值是否为null,然后检查它是否为BagCoffee,如果为,则current=current.next并再次调用hasNext()方法,否则返回true。很好,谢谢你的提示。
    if(!hasNext()) {
        current = current.next;
        return next();
    } else {
        //Stop executing method
    }