Iterator

不要只使用具体类来编程,要优先使用抽象类和接口来编程

/**
 * 用于遍历集合中的元素
 * 迭代器
 */
public interface Iterator {
    //判断是否存在下一个元素
    public abstract boolean hasNext();
    //获取下一个元素
    public abstract Object next();
}
/**
 * 生成一个用于遍历集合的迭代器
 * 集合
 */
public interface Aggregate {
    public abstract Iterator 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;
    }

    @Override
    public Iterator iterator() {//创建书架迭代器
        return new BookShelfIterator(this);
    }
}
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;
    }
}

/**
 * 书架迭代器
 */
public class BookShelfIterator implements Iterator {
    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;
    }
}
public class Main {
    public static void main(String[] args){
        BookShelf bookShelf = new BookShelf(4);
        bookShelf.appendBook(new Book("a"));
        bookShelf.appendBook(new Book("b"));
        bookShelf.appendBook(new Book("c"));
        bookShelf.appendBook(new Book("d"));
        Iterator it = bookShelf.iterator();
        //while不依赖BookShelf管理book用的数组还是其它,iterator只需正确返回iterator实例
        while (it.hasNext()){
            Book book = (Book) it.next();
            System.out.println(book.getName());
        }
    }
}

当书的数量超过最初指定的书架容量,就无法继续向添加了,我们将数组改为ArrayList


import java.util.ArrayList;

/**
 * 书架,书的集合类
 */
public class BookShelf implements Aggregate {
    private ArrayList<Book> books;
    private int last = 0;

    public BookShelf(int initialsize) {
        this.books = new ArrayList<>(initialsize);
    }
    public Book getBookAt(int index){
        return books.get(index);
    }

    public void appendBook(Book book){
        books.add(book);
    }

    public int getLength(){
        return books.size();
    }

    @Override
    public Iterator iterator() {//创建书架迭代器
        return new BookShelfIterator(this);
    }
}
原文地址:https://www.cnblogs.com/fly-book/p/12448311.html