黑马程序员技术交流社区

标题: 你知道集合在哪儿实现的迭代器接口吗? [打印本页]

作者: 黑马刘涛    时间: 2012-7-19 15:36
标题: 你知道集合在哪儿实现的迭代器接口吗?
本帖最后由 黑马刘涛 于 2012-7-19 15:40 编辑

1.迭代器设计
迭代器是一种模式,它可以使得对于序列类型的数据结构的遍历行为与被遍历的对象分离,即我们无需关心该序列的底层结构是什么样子的。
一般的迭代器对外提供的接口有:
[1]检查是否至序列末端;
[2]返回当前的对象;
[3]过渡到下一个对象。
使用一个ArrayList作为底层的数据结构
  1. package java.util;

  2. public interface Iterator<E> {
  3.     boolean hasNext();
  4.     E next();
  5.     void remove();
  6. }
复制代码
  1. import java.util.ArrayList;
  2. import java.util.Iterator;
  3. import java.util.List;

  4. public class Links3<T> {
  5.     private List<T> items = new ArrayList<T>();

  6.     public void add(T x) {
  7.        items.add(x);
  8.     }

  9.     public Iterator<T> iterator() {
  10.        return new Iterator<T>() {
  11.            private int index = 0;

  12.            public boolean hasNext() {
  13.               return index < items.size();
  14.            }

  15.            public T next() {
  16.               return items.get(index++);
  17.            }

  18.            public void remove() { // Not implemented
  19.               throw new UnsupportedOperationException();
  20.            }
  21.        };
  22.     }

  23.     public static void main(String[] args) {
  24.        Links3<Integer> links = new Links3<Integer>();
  25.        for (int i = 1; i < 6; i++)
  26.            links.add(i);
  27.        // use Standard Iterator
  28.        Iterator<Integer> myItr = links.iterator();
  29.        while (myItr.hasNext())
  30.            System.out.print(myItr.next() + " ");
  31.     }
  32. }
复制代码
看到了吗,
  1. public Iterator<T> iterator() {
  2.        return new Iterator<T>() {
  3.            private int index = 0;

  4.            public boolean hasNext() {
  5.               return index < items.size();
  6.            }

  7.            public T next() {
  8.               return items.get(index++);
  9.            }

  10.            public void remove() { // Not implemented
  11.               throw new UnsupportedOperationException();
  12.            }
  13.        };
  14.     }

复制代码
ArrayList类应该就是这么干的,Iterator所有已知实现类:
BeanContextSupport.BCSIterator, EventReaderDelegate, Scanner 没有我们常见的集合,我猜想ArrayList等其他类就是用一个匿名内部类实现了Iterator接口。然后你才有可能使用接口中声明的方法。





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2