fork download
  1. interface Aggregate {
  2. public abstract Iterator iterator();
  3. }
  4.  
  5. interface Iterator {
  6. public abstract boolean hasNext();
  7. public abstract Object next();
  8. }
  9.  
  10. class Book {
  11. private String name ="";
  12. public Book(String name) { this.name = name; }
  13. public String getName() { return name; }
  14. }
  15.  
  16. class BookShelf implements Aggregate {
  17. private java.util.ArrayList<Book> books;
  18. public BookShelf(int maxsize) { /* constructor */
  19. this.books = new java.util.ArrayList<Book>(maxsize);
  20. }
  21. Book getBookAt(int index) { /* called from iterator */
  22. return books.get(index);
  23. }
  24. public int getLength() { return books.size(); } /* called from iterator */
  25. public Iterator iterator() { /* called form iterator; make iterator */
  26. return new BookShelfIterator(this);
  27. }
  28. public void appendBook(Book book) { /* utility for main */
  29. this.books.add(book);
  30. }
  31. }
  32.  
  33. class BookShelfIterator implements Iterator {
  34. private BookShelf bookShelf;
  35. private int index;
  36.  
  37. public BookShelfIterator(BookShelf bookShelf) { /* constructor */
  38. this.bookShelf = bookShelf;
  39. this.index = 0;
  40. }
  41. public boolean hasNext() {
  42. if (index < bookShelf.getLength()) return true;
  43. else return false;
  44. }
  45. public Object next() {
  46. Book book = bookShelf.getBookAt(index);
  47. index++;
  48. return book;
  49. }
  50. }
  51.  
  52. class Main {
  53. public static void main(String[] args) {
  54. BookShelf bookShelf = new BookShelf(4);
  55. bookShelf.appendBook(new Book("Around the World in 80 Days"));
  56. bookShelf.appendBook(new Book("Bible"));
  57. bookShelf.appendBook(new Book("Cinderella"));
  58. bookShelf.appendBook(new Book("Daddy-Long-Legs"));
  59. bookShelf.appendBook(new Book("EinStein"));
  60. bookShelf.appendBook(new Book("Faraday"));
  61. Iterator it = bookShelf.iterator();
  62. while (it.hasNext()) {
  63. Book book = (Book)it.next();
  64. System.out.println("" + book.getName());
  65. }
  66. }
  67. }
  68. /* end */
  69.  
Success #stdin #stdout 0.06s 2841600KB
stdin
Standard input is empty
stdout
Around the World in 80 Days
Bible
Cinderella
Daddy-Long-Legs
EinStein
Faraday