黑马程序员技术交流社区
标题:
你知道集合在哪儿实现的迭代器接口吗?
[打印本页]
作者:
黑马刘涛
时间:
2012-7-19 15:36
标题:
你知道集合在哪儿实现的迭代器接口吗?
本帖最后由 黑马刘涛 于 2012-7-19 15:40 编辑
1.迭代器设计
迭代器是一种模式,它可以使得对于序列类型的数据结构的遍历行为与被遍历的对象分离,即我们无需关心该序列的底层结构是什么样子的。
一般的迭代器对外提供的接口有:
[1]检查是否至序列末端;
[2]返回当前的对象;
[3]过渡到下一个对象。
使用一个ArrayList作为底层的数据结构
package java.util;
public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}
复制代码
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Links3<T> {
private List<T> items = new ArrayList<T>();
public void add(T x) {
items.add(x);
}
public Iterator<T> iterator() {
return new Iterator<T>() {
private int index = 0;
public boolean hasNext() {
return index < items.size();
}
public T next() {
return items.get(index++);
}
public void remove() { // Not implemented
throw new UnsupportedOperationException();
}
};
}
public static void main(String[] args) {
Links3<Integer> links = new Links3<Integer>();
for (int i = 1; i < 6; i++)
links.add(i);
// use Standard Iterator
Iterator<Integer> myItr = links.iterator();
while (myItr.hasNext())
System.out.print(myItr.next() + " ");
}
}
复制代码
看到了吗,
public Iterator<T> iterator() {
return new Iterator<T>() {
private int index = 0;
public boolean hasNext() {
return index < items.size();
}
public T next() {
return items.get(index++);
}
public void remove() { // Not implemented
throw new UnsupportedOperationException();
}
};
}
复制代码
ArrayList类应该就是这么干的,Iterator所有已知实现类:
BeanContextSupport.BCSIterator, EventReaderDelegate, Scanner 没有我们常见的集合,我猜想ArrayList等其他类就是用一个匿名内部类实现了Iterator接口。然后你才有可能使用接口中声明的方法。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2