请教一个内部类的问题

04-06-20 zuolas168
试用内部类实现一个叠代器(iterator);

public class MemberContainer {
private String[] _members = {"A","B","C","D","E","E","F","F","G"};
public Iterator iterator() {
在此添加您的代码
}
在此添加你的内部类定义
}
您的任务是在MemberContainer内定义并在iterator()方法里面返回一个Iterator对象,以便对数组
_members里面的内容进行遍历,额外的限制是:以“#”开头的元素忽略掉,在上例中。遍历结果是
"A","B","C","D","E","F","G"。把数组内容换成{"A","B","C","D","D"},{"A","B","C","D"},{"A","B","C","D"},分别对您的代码进行测试。程序如下:

import java.util.*;

public class IterTest {

public static void main(String[] args)throws Exception {
MemberContainer members = new MemberContainer();
Iterator iter = members.iterator();

while(iter.hasNext()){
Object obj = iter.next();
System.out.println(obj.toString());
}
}
}

wwlhp@jdon
2004-06-21 17:26
是不是面试的题目啊:)
在java集合框架中有很多这样的例子,建议你看一下java.util.ArrayList的源码,里面有一个内部类实现了Iterator接口,对数组遍历。