【发布时间】:2015-06-07 20:10:46
【问题描述】:
在阅读Generators 上的维基百科文章时,我发现以下 Java 实现迭代泛型类型 Iterator<Integer> 会产生无限的斐波那契数序列
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() } -
不是。那不会编译。写它的人犯了一个错误。
-
修正了维基百科上的例子。