Skip to content
Advertisement

How can I make my class iterable so I can use foreach syntax?

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 says:

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

How can I get this working?

Advertisement

Answer

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();
    }

    ...
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement