标签:list static crete 根据 [] this 总结 迭代 OLE
public class Book { private String name; public Book(String name){ this.name=name; } public String getName() { return name; } }
public interface Iterator { public abstract boolean hasNext(); public abstract Object next(); }
定义书架类集合
import java.util.ArrayList; import java.util.List; public class BookShelf extends Aggregate { private List<Book> bookList = new ArrayList<>(); public void addBook(Book book) { bookList.add(book); } public Book getIndex(int i) { return bookList.get(i); } public int getLength() { return bookList.size(); } @Override public Iterator iterator() { return new BookShelfIterator(this); } }
定义书架类对应的书架遍历类
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(bookShelf.getLength()>index) { return true; } return false; } @Override public Object next() { Book book = bookShelf.getIndex(index); index++; return book; } }
定义测试类
public class Main { public static void main(String[] args){ BookShelf bookShelf = new BookShelf(); bookShelf.addBook(new Book("数学")); bookShelf.addBook(new Book("物理")); bookShelf.addBook(new Book("化学")); Iterator iterator = bookShelf.iterator(); for(;iterator.hasNext();) { Book book = (Book)iterator.next(); System.out.println(book.getName()); } } }
总结:被遍历的集合类(BookShelf)与遍历类(BookShelfIterator)分开定义,进行解耦,方便扩展。
标签:list static crete 根据 [] this 总结 迭代 OLE
原文地址:https://www.cnblogs.com/use-D/p/9545491.html