How can I make my class iterable so I can use foreach syntax?
Implement the Iterable
interface. That means you need to implement a method that returns an Iterator
object that will iterate over the elements of a BookList
.
In this case, your iterator()
method could just return the result of calling bList.iterator()
. (That will cause for (Book b : somBookList)
to iterate over the Book
objects in the BookList.bList
... )
In other cases, you might need to write your own Iterator<T>
implementation class, complete with T next()
, boolean hasNext()
and remove()
methods. For instance, if you wanted to prevent external code from removing elements from the BookList
via your iterator, you might implement it like this:
public class BookList implements Iterable<Book> {
private final List<Book> bList = new ArrayList<Book>();
//...
@Override
public Iterator<Book> iterator() {
return new Iterator<Book> () {
private final Iterator<Book> iter = bList.iterator();
@Override
public boolean hasNext() {
return iter.hasNext();
}
@Override
public Book next() {
return iter.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException("no changes allowed");
}
};
}
}
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();
}
...
}