Skip to content

Instantly share code, notes, and snippets.

@ayato-p
Created November 26, 2012 05:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayato-p/4146714 to your computer and use it in GitHub Desktop.
Save ayato-p/4146714 to your computer and use it in GitHub Desktop.
import java.util.Iterator;
public interface Aggregate {
public abstract Iterator<Book> iterator();
}
public class Book {
private String name;
public Book(String name) {
this.name = name;
}
public String getName(){
return this.name;
}
}
import java.util.Iterator;
public class BookShelf implements Aggregate{
private Book[] books;
private int last = 0;
public BookShelf(int maxsize) {
this.books = new Book[maxsize];
}
public Book getBookAt(int index){
return books[index];
}
public void appendBook(Book book){
this.books[last] = book;
last++;
}
public int getLength(){
return last;
}
public Iterator<Book> iterator(){
return new BookShelfIterator(this);
}
}
import java.util.Iterator;
public class BookShelfIterator implements Iterator<Book> {
private BookShelf bookShelf;
private int index;
public BookShelfIterator(BookShelf bookShelf) {
this.bookShelf = bookShelf;
this.index = 0;
}
@Override
public boolean hasNext() {
if(index < bookShelf.getLength()){
return true;
}
return false;
}
@Override
public Book next() {
Book book = bookShelf.getBookAt(index);
index++;
return book;
}
@Override
public void remove() {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment