阅读以下说明和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());
}
}
}
(1)implements this iterator() it.hasNext() next() 解析:Iterator是接口类,空(1)应该填implements。
根据构造函数Bookshelflterator(BookshelfbookShelf)可得,空(2)应填this,即自身引用。
空(3)是取得迭代器实例,BookShelf类方法iterator()是返回Iterator接口,故空(3)应填iterator()。
while循环是遍历书架,输出书名,循环条件是“还有下一记录(书)”,故空(4)应填it.hasNext()。注意指针写法。
空(5)是取得书实例,BookShelf类中方法next()是返回Object类实例,取得下一本书,故空(5)应填next()。
请问韩国有多少年历史?他们的历史是不是和我们国家历史差不多啊?请问韩国有多少年历史?他们的历史是不 其他 2020-05-16 …
历史-历史上重大改革回眸王安石变法在取得成效的同时,也存在诸多问题,值得深思。阅读下列材料,回答问 历史 2020-06-09 …
阅读材料,回答问题。人类在漫长的历史长河中,创造和发展了多姿多彩的文明。经历了5000多年的历史变迁 政治 2020-11-05 …
有效获取和正确解读历史信息,是研习历史的重要前提。阅读材料,回答问题。材料一文字资料“苏城机户类多雇 历史 2020-12-04 …
论证历史,探究历史,运用新史观解读历史是历史学习的重要组成部分。阅读材料,回答问题。材料一斯密认为, 历史 2020-12-05 …
(26)阅读材料,回答问题。2013年6月22日,云南红河哈尼梯田历经13年“申遗”成功。哈尼梯田, 政治 2020-12-08 …
阅读材料,回答问题。2013年6月22日,云南红河哈尼梯田历经13年“申遗”成功。哈尼梯田,是哈尼族 政治 2020-12-08 …
英语翻译我对历史很感兴趣,但我对欧洲和其它国家的历史不太熟悉,如果将来我有时间的话会多了解的,因为读 英语 2020-12-19 …
历史信息浩如烟海,多种多样。有效获取和正确解读历史信息,是研习历史的重要前提。阅读材料,结合所学完成 其他 2020-12-26 …
(26分)阅读材料,回答问题。材料一南京是我国著名的历史文化名城之一,与北京、西安、洛阳、开封、杭州 政治 2021-01-17 …