java - 如何使我的类可迭代,以便我可以使用 foreach 语法?

标签 java foreach iterable

我有 BookBookList 类。 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/

相关文章:

java - Spring Boot : How do you specify an environment variable that has dashes in the application. 属性?

c# - 在 C# 中循环遍历两个集合以比较相同的集合

javascript - 为什么console.log 在作为参数传递给forEach 时不起作用?

python - 使用 zip 扩展迭代后检查可迭代?

java - Java 中的迭代器行为

python - 为什么在 iterable 上调用 list() 会改变它?

java - 我们如何在不使用任何内置函数的情况下在 Java 中找到 String 的长度? (甚至不是 charAt() 或 toCharArray() 或 length())

java - 删除数组中两个或多个以6结尾的连续数字

java - 我是否正确使用 Apache Camel 聚合器?

php - 根据属性值选择对象的对象数组