【问题标题】:Iterating over an object of type Iterator<T>迭代 Iterator<T> 类型的对象
【发布时间】:2015-06-07 20:10:46
【问题描述】:

在阅读Generators 上的维基百科文章时,我发现以下 Java 实现迭代泛型类型 Iterator&lt;Integer&gt; 会产生无限的斐波那契数序列

Iterator<Integer> fibo = new Iterator<Integer>() {
    int a = 1;
    int b = 1;
    int total;

    @Override
    public boolean hasNext() {
        return true;
    }

    @Override
    public Integer next() {
        total = a + b;
        a = b;
        b = total;
        return total;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }
}
// this could then be used as...
for(int f: fibo) {
    System.out.println("next Fibonacci number is " + f);
    if (someCondition(f)) break;
} 

但是,上面的代码放在类的main 方法中时不起作用。它说

Can only iterate over an array or an instance of java.lang.Iterable

这是可以理解的。这是否意味着上面的例子是错误的或不完整的?我错过了什么吗?

【问题讨论】:

  • Iterator 不是 Iterable
  • @SotiriosDelimanolis 谢谢,我知道,但我在询问维基百科页面上的代码 sn-p。它应该如何工作?
  • @ajay 类似:while(hasNext() ) { next() }
  • 不是。那不会编译。写它的人犯了一个错误。
  • 修正了维基百科上的例子。

标签: java iterator iteration


【解决方案1】:

Wikipedia 上的代码示例无效,但无论如何您都可以轻松迭代,只需显式调用 hasNext()next()

// We know that fibo.hasNext() will always return true, but
// in general you don't...
while (fibo.hasNext()) {
    int f = fibo.next();
    System.out.println("next Fibonacci number is " + f);
    if (someCondition(f)) break;
}

【讨论】:

    【解决方案2】:

    删除 for 循环并使用 while 循环。由于迭代器不是数组类型或集合。 试试这个

    while(fibo.hasNext()) {
        System.out.println(fibo.next());
    

    }

    【讨论】:

      猜你喜欢
      • 2016-05-07
      • 2015-11-28
      • 1970-01-01
      • 2019-04-26
      • 2011-01-10
      • 1970-01-01
      • 1970-01-01
      • 2014-07-09
      • 1970-01-01
      相关资源
      最近更新 更多