[英]Java Explicit iterator works. Implicit forloop yields “Can only iterate over an array or an instance of java.lang.Iterable”
I've implemented Iterable<> in my base class but the subclass will not allow an implicit forloop. 我已经在基类中实现了Iterable <>,但是子类将不允许隐式的forloop。
Why is the Iterator<> working correctly but the for-loop complaining of 为什么Iterator <>正常工作,但是for循环抱怨
Can only iterate over an array or an instance of java.lang.Iterable
I would have expected the Iterable<> interface to be visible in the subclass. 我本来希望Iterable <>接口在子类中可见。 What am I missing?
我想念什么?
package tester;
import java.util.ArrayList;
import java.util.Iterator;
public class TestInher {
private Concrete<Integer> mList = new Concrete<Integer>();
public TestInher() {}
public abstract class Base<T>
implements Iterable<T>
{
protected ArrayList<T> list = new ArrayList<T>();
@Override
public Iterator<T> iterator() {return list.iterator();}
public abstract void add(T item);
}
public abstract class ClassAbstract<T> extends Base<T>{}
public class Concrete<T>
extends ClassAbstract<T>
{
@Override
public void add(T item) {list.add(item);}
}
public void doIt() {
for(int i=0; i<10; i++) {mList.add(i);}
Iterator<Integer> i = mList.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
//Can only iterate over an array or an instance of java.lang.Iterable
for(Integer i : mList.iterator()) {
}
}
}
In the enhanced for
loop, you iterate over the Iterable
, not over the Iterator
. 在增强的
for
循环中,您遍历Iterable
,而不遍历 Iterator
。 The Iterable
gets the Iterator
that is implicitly used in this loop, but an Iterable
is not itself the Iterator
. Iterable
获取在此循环中隐式使用的Iterator
,但是Iterable
本身不是Iterator
。 Try the Iterable
itself. 尝试
Iterable
本身。
for (Integer i : mList) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.