【发布时间】:2019-10-27 22:53:43
【问题描述】:
下面的代码给了我不编译给我以下错误:“foreach 不适用于类型 'Bag'”。
我不明白问题出在哪里,因为“Bag”类正在实现“Iterable”,所以我猜,循环应该将“Bag”视为“Iterable”。请问,你能帮我澄清一下情况吗?
class Bag<Item> implements Iterable<Item> {
private Node first;
private class Node {
Item item;
Node next;
}
public void add(Item item) {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
}
public Iterator<Item> iterator() {
return new ListIterator();
}
private class ListIterator implements Iterator<Item> {
private Node current = first;
public boolean hasNext() {
return current != null;
}
public void remove() {}
public Item next() {
Item item = current.item;
current = current.next;
return item;
}
}
public static void main(String[] args) {
Bag<Integer> a = new Bag();
a.add(5);
a.add(10);
for (int w : a) {
System.out.println(w.iterator());
}
}
}
【问题讨论】:
-
包从何而来?如果不编译就不能实现Iterable。
-
其实it works对我来说
标签: java loops iterator iteration iterable