我有 Book
和 BookList
类。 BookList
是这样的:
public class BookList
{
private final List<Book> bList = new ArrayList<Book>();
public int size() { return bList.size(); }
public boolean isEmpty() { ... }
public boolean contains(Book b) { ... }
public boolean add(Book b) { ... }
public boolean remove(Book b) { .. }
public void clear() { ... }
public Book get(int index) { ... }
}
在我的主课中,我想在 for each 循环中打印书名:
for(Book b : bList)
{
b.print();
}
Eclipse 说:
Can only iterate over an array or an instance of java.lang.Iterable
我怎样才能让它工作?
最佳答案
您需要实现 Iterable
接口(interface),这意味着您需要实现 iterator()
方法。在您的情况下,这可能看起来像这样:
public class BookList implements Iterable<Book> {
private final List<Book> bList = new ArrayList<Book>();
@Override
public Iterator<Book> iterator() {
return bList.iterator();
}
...
}
关于java - 如何使我的类可迭代,以便我可以使用 foreach 语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21512250/