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

mk_ picture mk_ · Feb 2, 2014 · Viewed 40.5k times · Source

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?

Answer

andersschuller picture andersschuller · Feb 2, 2014

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

    ...
}