-
- package com.yjwang.Iterator;
- public interface Aggregate {
- public abstract Iterator iterator();
- }
- package com.yjwang.Iterator;
- package com.yjwang.Iterator;
- public interface Iterator {
- public abstract boolean hasNext();
- public abstract Object Next();
- }
- package com.yjwang.Iterator;
- public class Book {
- private String name;
- public Book(String name){
- this.name = name;
- }
- public String getName(){
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
- package com.yjwang.Iterator;
- import java.util.Vector;
- public class BookShelf implements Aggregate{
- //private Book[] books;
- private Vector books;
- private int last = 0;
- /**定义书架的长度***/
- public BookShelf(int maxsize) {
- //this.books = new Book[maxsize];
- this.books = new Vector(maxsize);
- }
- public Book getBookAt(int index){
- //return books[index];
- return (Book)books.get(index);
- }
- public void appendBook(Book book){
- //this.books[last] = book;
- books.add(book);
- //last++;
- }
- /**统计书的总数**/
- public int getLength(){
- //return last;
- return books.size();
- }
- public Iterator iterator(){
- return new BookShelfIterator(this);
- }
- }
- package com.yjwang.Iterator;
- public class BookShelfIterator implements Iterator {
- private BookShelf bookShelf;
- private int index;
- public BookShelfIterator(BookShelf bookShelf){
- this.bookShelf = bookShelf;
- this.index = 0;
- }
- public boolean hasNext() {
- // TODO Auto-generated method stub
- if(index < bookShelf.getLength()){
- return true;
- }
- else{
- return false;
- }
- }
- public Object Next() {
- // TODO Auto-generated method stub
- Book book = bookShelf.getBookAt(index);
- index++;
- return book;
- }
- }
- package com.yjwang.Iterator;
- public class MainTest {
- public static void main(String args[]){
- BookShelf bookShelf = new BookShelf(4);
- bookShelf.appendBook(new Book("A_book1"));
- bookShelf.appendBook(new Book("B_book2"));
- bookShelf.appendBook(new Book("C_book3"));
- bookShelf.appendBook(new Book("D_book4"));
- bookShelf.appendBook(new Book("E_book5"));
- Iterator it = bookShelf.iterator();
- while(it.hasNext()){
- Book book = (Book)it.Next();
- System.out.println(" " + book.getName());
- }
- }
- }