我怎样才能使我的类迭代,所以我可以使用foreach语法? [英] How can I make my class iterable so I can use foreach syntax?
本文介绍了我怎样才能使我的类迭代,所以我可以使用foreach语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 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 Object get(int index){...}
$ b $ / code>
在我的主类中,我想要在每个循环中打印书籍的标题:
for(Book b :bList)
{
b.print();
$ / code
Eclipse说:
< blockquote>
只能遍历数组或java.lang.Iterable的实例
得到这个工作吗?
解决方案您需要实现 Iterable
界面,这意味着您需要实现迭代器()
方法。在你的情况下,这可能看起来像这样:
public class BookList implements Iterable< Book> {
private final List< Book> bList = new ArrayList< Book>();
@Override
public Iterator< Book> iterator(){
return bList.iterator();
}
...
}
I have Book
and BookList
classes. BookList
is something like this:
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 Object get(int index) { ... }
}
In my main class I want to print titles of books with in a for each loop:
for(Book b : bList)
{
b.print();
}
Eclipse says:
Can only iterate over an array or an instance of java.lang.Iterable
How can I get this working?
解决方案 You need to implement the Iterable
interface, which means you need to implement the iterator()
method. In your case, this might look something like this:
public class BookList implements Iterable<Book> {
private final List<Book> bList = new ArrayList<Book>();
@Override
public Iterator<Book> iterator() {
return bList.iterator();
}
...
}
这篇关于我怎样才能使我的类迭代,所以我可以使用foreach语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文