阅读以下说明和Java代码,回答问题[说明] 对多个元素的聚合进行遍历访问时,需要依次推移元素,例如
阅读以下说明和Java代码,回答问题
[说明]
对多个元素的聚合进行遍历访问时,需要依次推移元素,例如对数组通过递增下标的方式,数组下标功能抽象化、一般化的结果就称为迭代器(Iterator)。模式以下程序模拟将书籍(Book)放到书架(BookShelf)上并依次输出书名。这样就要涉及到遍历整个书架的过程。使用迭代器Iterator实现。图6-1显示了各个类间的关系。以下是JAVA语言实现,能够正确编译通过。
[图6-1]
[Java代码]
//Iterator. java文件
public interface Iterator {
public abstract boolean hasNext();
public abstract Object next();
}
//Aggregate. java文件
public interface Aggregate {
public abstract Iterator iterator();
}
//Book. java
public class Book {
//省略具体方法和属性
}
//BookshelfIterator. java文件
public class Bookshelf工terator (1) 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()f//取得下一个元素
Book book = bookShelf. getBookAt(index);
index++;
return book;
}
}
//BookShelf. java
import java. util. Vector;
public class BookShelf {
private Vector books;
public BookShelf(int initialsize){
this. books = new Vector(initialsize);
}
public Book getBookAt(int index){
return(Book)books.get(index);
}
public int getLength(){
return books.size();
}
public Iterator iterator(){
return new BookShelfIterator( (2) );
}
}
//Main. java文件
public class Main {
public static void main(String args){
BookShelf bookShelf = new BookShelf(4);
//将书籍上架,省略代码
Iterator it = bookShelf. (3) ;
while( (4) ){//遍历书架,输出书名
Book book = (Book)it. (5) ;
System.out.printin(" "+book.getName());
}
}
}
参考答案: