如何使我的类可迭代,以便我可以使用 foreach 语法? [英] How can I make my class iterable so I can use foreach syntax?

查看:21
本文介绍了如何使我的类可迭代,以便我可以使用 foreach 语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 BookBookList 类.BookList 是这样的:

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 Book 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 说:

只能迭代数组或 java.lang.Iterable 的实例

Can only iterate over an array or an instance of java.lang.Iterable

我怎样才能让它工作?

推荐答案

你需要实现Iterable 接口,这意味着您需要实现 iterator() 方法.在您的情况下,这可能如下所示:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆