美文网首页
Iterator实现

Iterator实现

作者: 492284513d5a | 来源:发表于2019-01-16 20:18 被阅读0次
  • Aggregate接口

public interface Aggregate{
    public abstract Iterator iterator();
}
  • Iterator接口

public interface Iterator{
   public abstract boolean hasNext();
   public abstract Object next();
}
  • Book类

public class Book{
    private String name;
    public Book(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }
}
  • BookShelf类

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 iterator(){
        return new BookShelfIterator(this);
   }
}
  • BookShelfIterator类

public class BookShelfIterator implments Iterator{
    private BookShelf bookShelf;
    private int  index;
    public BookShelfIterator(BookShelf bookShelf) {
        this.bookShelf = bookShelf;
        this.index = 0;
}
   public  boolean hasNext(){
       if(index<bookShelf.getLength()) {
           return true;
      }else{
           return false;
       }
   }
  public Object next(){
      Book book  = bookShelf.getBookAt(index);
      index++;
      return book;
   } 
}
  • Main类

public class Main{
    public static void main(String[] args){
        BookShelf bookShelf = new BookShelf(4);
        bookShelf.appendBook(new Book("Around the World in 80 Days"));
        bookShelf.appendBook(new Book("Bible"));
        bookShelf.appendBook(new Book("Cinderella"));
        bookShelf.appendBook(new Book("Daddy -Long-Legs"));
        Iterator it  = bookShelf.iterator();
        while(it.hasNext()){
              Book book = (Book)it.next();
              System.out.println(book.getName());
         }    
    }
}

相关文章

网友评论

      本文标题:Iterator实现

      本文链接:https://www.haomeiwen.com/subject/bkxsdqtx.html