58 lines
1.6 KiB
Java
58 lines
1.6 KiB
Java
package iterator;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
|
|
/**
|
|
* Aggregate — the collection. Exposes iterators without
|
|
* revealing its internal storage structure.
|
|
*/
|
|
public class BookShelf {
|
|
private final List<Book> books = new ArrayList<>();
|
|
|
|
public void addBook(Book book) { books.add(book); }
|
|
|
|
/** Standard forward iterator */
|
|
public BookIterator iterator() {
|
|
return new ForwardIterator();
|
|
}
|
|
|
|
/** Filtered iterator — only books from a specific decade */
|
|
public BookIterator iteratorByDecade(int decade) {
|
|
return new DecadeIterator(decade);
|
|
}
|
|
|
|
// --- Inner iterator implementations ---
|
|
|
|
private class ForwardIterator implements BookIterator {
|
|
private int index = 0;
|
|
|
|
@Override public boolean hasNext() { return index < books.size(); }
|
|
@Override public Book next() { return books.get(index++); }
|
|
}
|
|
|
|
private class DecadeIterator implements BookIterator {
|
|
private final int decade;
|
|
private int index = 0;
|
|
private Book nextBook;
|
|
|
|
DecadeIterator(int decade) {
|
|
this.decade = decade;
|
|
advance();
|
|
}
|
|
|
|
private void advance() {
|
|
nextBook = null;
|
|
while (index < books.size()) {
|
|
Book b = books.get(index++);
|
|
if (b.getYear() / 10 * 10 == decade) { nextBook = b; break; }
|
|
}
|
|
}
|
|
|
|
@Override public boolean hasNext() { return nextBook != null; }
|
|
@Override public Book next() {
|
|
Book b = nextBook; advance(); return b;
|
|
}
|
|
}
|
|
}
|