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:

JavaScript

In my main class I want to print titles of books with in a for each loop:

JavaScript

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:

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