Iterable<Position<Integer>> iterable = list.positions();
Iterator<Position<Integer>> iter = iterable.iterator();
while (iter.hasNext()) {
System.out.println(iter.next().getData());
}
Run Code Online (Sandbox Code Playgroud)
上面的代码没有问题.list只是我写的List类的一个实例.它包含Integer类型的元素.
for (Position<Integer> pos : iterable) {
}
Run Code Online (Sandbox Code Playgroud)
此代码在冒号后面的部分失败.这应该等同于第一段代码,即带有while循环的代码.所以我不明白为什么for-each循环有错误.错误说:"只能迭代数组或java.lang.Iterable的实例" - 但iterable已经是Iterable,不是吗?我在这里错过了什么?
以下是实现上述方法和类型的完整代码.
private class PositionIterator implements Iterator<Position<E>> {
private Position<E> cursor = first();
private Position<E> current = null;
public boolean hasNext() {
return cursor.getData() != null;
}
public Position<E> next() {
if (cursor == null) throw new NoSuchElementException("reached the end of the list");
current = cursor;
cursor = after(cursor);
return current;
}
}
private class PositionIterable implements Iterable<Position<E>> {
public Iterator<Position<E>> iterator() {
return new PositionIterator();
}
}
public Iterable<Position<E>> positions() {
return new PositionIterable();
}
Run Code Online (Sandbox Code Playgroud)
这些是在另一个名为的类中的嵌套类PositionalList<E>.为了保持这篇文章的紧凑性,我决定省略外面的课程.它只是一堆getter和setter方法,是List类的典型方法.
public interface Iterable<E> {
public Iterator<E> iterator();
}
Run Code Online (Sandbox Code Playgroud)
^这是由I实现的Iterable接口 PositionIterable
public interface Iterator<E> {
boolean hasNext();
E next();
}
Run Code Online (Sandbox Code Playgroud)
那就是Iterator界面.
增强的for循环接受一个Iterable,而不是一个Iterator.iter是一个Iterator.
因此:
for (Position<Integer> pos : iter)
Run Code Online (Sandbox Code Playgroud)
应该 :
for (Position<Integer> pos : iterable)
Run Code Online (Sandbox Code Playgroud)
编辑:根据评论,您的问题必须java.lang.Iterable由您的自定义Iterable界面隐藏.如果您的iterable变量属于自定义Iterable接口的类型,则接受的增强型for循环不能使用它java.lang.Iterable.
| 归档时间: |
|
| 查看次数: |
81 次 |
| 最近记录: |