Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 276
b4da Avatar asked Feb 02 '14 15:02

b4da


1 Answers

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();     }      ... } 
like image 191
andersschuller Avatar answered Oct 02 '22 18:10

andersschuller