天天看点

从Java Collections源码分析迭代器模式

原文:http://blog.csdn.net/mudalu626/article/details/6457427

一、 引言

  

  迭代这个名词对于熟悉Java的人来说绝对不陌生。我们常常使用JDK提供的迭代接口进行java collection的遍历:

  

  Iterator it = list.iterator();

  while(it.hasNext()){

  //using “it.next();”do some businesss logic

  }

  

  而这就是关于迭代器模式应用很好的例子。

  

  二、 定义与结构

  

  迭代器(Iterator)模式,又叫做游标(Cursor)模式。GOF给出的定义为:提供一种方法访问一个容器(container)对象中各个元素,而又不需暴露该对象的内部细节。

  

  从定义可见,迭代器模式是为容器而生。很明显,对容器对象的访问必然涉及到遍历算法。你可以一股脑的将遍历方法塞到容器对象中去;或者根本不去提供什么遍历算法,让使用容器的人自己去实现去吧。这两种情况好像都能够解决问题。

  

  然而在前一种情况,容器承受了过多的功能,它不仅要负责自己“容器”内的元素维护(添加、删除等等),而且还要提供遍历自身的接口;而且由于遍历状态保存的问题,不能对同一个容器对象同时进行多个遍历。第二种方式倒是省事,却又将容器的内部细节暴露无遗。

  

  而迭代器模式的出现,很好的解决了上面两种情况的弊端。先来看下迭代器模式的真面目吧。

  

  迭代器模式由以下角色组成:

  

  1) 迭代器角色(Iterator):迭代器角色负责定义访问和遍历元素的接口。

  

  2) 具体迭代器角色(Concrete Iterator):具体迭代器角色要实现迭代器接口,并要记录遍历中的当前位置。

  

  3) 容器角色(Container):容器角色负责提供创建具体迭代器角色的接口。

  

  4) 具体容器角色(Concrete Container):具体容器角色实现创建具体迭代器角色的接口——这个具体迭代器角色于该容器的结构相关。

  

  迭代器模式的类图如下:

从Java Collections源码分析迭代器模式

  

  三、 从Java Collections源码分析迭代器模式

  下面我们拿出java中Iterator的源码相关源码进行分析。

  下图是Java Collections的整体关系图:

从Java Collections源码分析迭代器模式

 

  从图中很容易看出,Collection和代表相应的抽象容器角色,而Iterator和ListIterator则代表相应的抽象迭代器角色。

  其中ListIterator是Iterator的子接口,扩充了向后遍历的方法接口。

  以下是Collection,Iterator,List及ListIterator的代码片段:

Collection:

[java] view plain copy

  1. //Collection继承自Iterable接口,而Iterable就是用来生产Iterator的接口  
  2. public interface Collection<E> extends Iterable<E> {  
  3. ...  
  4.     //继承自Iterable的方法,实现Collection和Iterator的耦合  
  5.     Iterator<E> iterator();  
  6. ...  
  7. }  

Iterator:

[java] view plaincopy

  1. public interface Iterator<E> {  
  2.     boolean hasNext();//如果仍有元素可以迭代,则返回 true。  
  3.     E next();//返回迭代的下一个元素。  
  4.     void remove();//从迭代器指向的集合中移除迭代器返回的最后一个元素(可选操作)。  
  5. }  

List:

[java] view plaincopy

  1. //List继承自Collection  
  2. public interface List<E> extends Collection<E> {  
  3.     Iterator<E> iterator();//List和Iterator的耦合  
  4.     ListIterator<E> listIterator();//List和ListIterator的耦合  
  5.     ListIterator<E> listIterator(int index);//从列表的指定位置开始  
  6. }  

ListIterator:

[java] view plaincopy

  1. //ListIterator继承自Iterator  
  2. public interface ListIterator<E> extends Iterator<E> {  
  3.     boolean hasNext();//以正向遍历列表时,如果列表迭代器有多个元素,则返回 true(换句话说,如果 next 返回一个元素而不是抛出异常,则返回 true)  
  4.     E next();//返回列表中的下一个元素  
  5.     boolean hasPrevious();//如果以反向遍历列表,列表迭代器有多个元素,则返回 true  
  6.     E previous();//返回列表中的前一个元素  
  7.     int nextIndex();//返回对 next 的后续调用所返回元素的索引  
  8.     int previousIndex();//返回对 previous 的后续调用所返回元素的索引  
  9.     void remove();//从列表中移除由 next 或 previous 返回的最后一个元素(可选操作)  
  10.     void set(E e);//用指定元素替换 next 或 previous 返回的最后一个元素(可选操作)  
  11.     void add(E e);//将指定的元素插入列表(可选操作)  
  12. }  

  那么具体容器角色和具体迭代器角色是那些类呢?

  首先先从Iterator入手,让我们先回到图上,熟悉Java Collections框架的朋友很容易明白Collection的实现类很多,它是Java Collections框架的顶层结构,它的下层又分Set和List两个分支,那我们就分别来分析这两个分支具体的具体实现。

  List的第一级实现类为AbstractList,java在此类中实现了具体容器角色和具体迭代器角色,那如何能在一个类中实现两个角色呢,还是从代码入手吧:

[java] view plain copy

  1. //AbstractList实现类List接口  
  2. public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {  
  3.     ...  
  4.     //已从结构上修改 此列表的次数。从结构上修改是指更改列表的大小,或者以其他方式打乱列表,使正在进行的迭代产生错误的结果  
  5.     protected transient int modCount = 0;  
  6.     ...  
  7.     //生产迭代器,每次生产一个新的对象,所以对同一个容器对象,可以同时进行多个遍历  
  8.     public Iterator<E> iterator() {  
  9.     return new Itr();  
  10.     }  
  11.     ...  
  12.     //这就是解决一个类实现两个角色的关键,用了一个私有内部类来实现了Iterator  
  13.     private class Itr implements Iterator<E> {  
  14.         //游标,也就是被遍历具体容器(AbstractList)的当前索引值  
  15.     int cursor = 0;  
  16.         //离游标最近的索引值,主要用在remove方法中,下面会详细说明  
  17.     int lastRet = -1;  
  18.         //此变量用作跟踪具体容器(AbstractList)的modCount变量,如果不一致则报错  
  19.     int expectedModCount = modCount;  
  20.         //原来hasNext的实现如此简单,用游标和具体容器的size进行比较即可,游标的操作见next方法  
  21.     public boolean hasNext() {  
  22.             return cursor != size();  
  23.     }  
  24.         //next方法也不难嘛,就是利用游标一次一次对具体容器进行遍历  
  25.     public E next() {  
  26.             //检查迭代器运行期间,容器结构是否修改,如修改则报错  
  27.             checkForComodification();  
  28.         try {  
  29.                 //呵呵,终于找到你了,原来又是用具体容器的方法实现的,这就是隐藏容器细节的关键  
  30.         E next = get(cursor);  
  31.                 //记录被返回的索引位置,并使游标向前移动  
  32.         lastRet = cursor++;  
  33.                 //返回被迭代的当前对象  
  34.         return next;  
  35.         } catch (IndexOutOfBoundsException e) {  
  36.         checkForComodification();  
  37.         throw new NoSuchElementException();  
  38.         }  
  39.     }  
  40.         //不用说了,remove方法的实现肯定也是借了容器之力  
  41.     public void remove() {  
  42.         if (lastRet == -1)  
  43.         throw new IllegalStateException();  
  44.             checkForComodification();  
  45.         try {  
  46.                 //嘿嘿,又是隐藏细节  
  47.         AbstractList.this.remove(lastRet);  
  48.         if (lastRet < cursor)  
  49.             cursor--;  
  50.         lastRet = -1;  
  51.                 //因为remove方法改变了容器结构,所以需要同步一下expectedModCount变量使修改次数一致  
  52.         expectedModCount = modCount;  
  53.         } catch (IndexOutOfBoundsException e) {  
  54.         throw new ConcurrentModificationException();  
  55.         }  
  56.     }  
  57.         //检查迭代器运行期间,容器结构是否修改,如修改则报错  
  58.     final void checkForComodification() {  
  59.         if (modCount != expectedModCount)  
  60.         throw new ConcurrentModificationException();  
  61.     }  
  62.     }  
  63.     ...  
  64.     //同理,ListIterator的实现类也作为容器的私有内部类出现  
  65.     private class ListItr extends Itr implements ListIterator<E> {  
  66.         //具体实现就不介绍了,和Iterator大同小异  
  67.     ListItr(int index) {  
  68.         cursor = index;  
  69.     }  
  70.     public boolean hasPrevious() {  
  71.         return cursor != 0;  
  72.     }  
  73.         public E previous() {  
  74.             checkForComodification();  
  75.             try {  
  76.                 int i = cursor - 1;  
  77.                 E previous = get(i);  
  78.                 lastRet = cursor = i;  
  79.                 return previous;  
  80.             } catch (IndexOutOfBoundsException e) {  
  81.                 checkForComodification();  
  82.                 throw new NoSuchElementException();  
  83.             }  
  84.         }  
  85.     public int nextIndex() {  
  86.         return cursor;  
  87.     }  
  88.     public int previousIndex() {  
  89.         return cursor-1;  
  90.     }  
  91.     public void set(E e) {  
  92.         if (lastRet == -1)  
  93.         throw new IllegalStateException();  
  94.             checkForComodification();  
  95.         try {  
  96.         AbstractList.this.set(lastRet, e);  
  97.         expectedModCount = modCount;  
  98.         } catch (IndexOutOfBoundsException ex) {  
  99.         throw new ConcurrentModificationException();  
  100.         }  
  101.     }  
  102.     public void add(E e) {  
  103.             checkForComodification();  
  104.         try {  
  105.         AbstractList.this.add(cursor++, e);  
  106.         lastRet = -1;  
  107.         expectedModCount = modCount;  
  108.         } catch (IndexOutOfBoundsException ex) {  
  109.         throw new ConcurrentModificationException();  
  110.         }  
  111.     }  
  112.     }  
  113. }  

      对于再下层的实现类,可以灵活的重写生产方法,并实现专用的迭代器内部类。

  Set和List不同,它的下一层没有实现类,而是俩个接口(AbstractSet和SortedSet),再往下一层找便是我们熟悉的两个实现类HashSet和TreeSet,而了解Java Collection的读者会知道,HashSet和TreeSet其实是借助Map系的HashMap和TreeMap实现的,所以具体实现方法是在Map系中的实现类中实现的(隐藏够深的)。因为涉及的两个对象数据结构稍微有些复杂(散列表和红黑树),可以在此处了解其内部构造。废话少说,上代码:

[java] view plain copy

  1. public class HashMap<K,V>  
  2.     extends AbstractMap<K,V>  
  3.     implements Map<K,V>, Cloneable, Serializable  
  4. {  
  5.     ...  
  6.     //已从结构上修改 此列表的次数。  
  7.     transient volatile int modCount;  
  8.     ...  
  9.     //因散列表结构的特殊性,需要分别实现三个迭代器KeyIterator、ValueIterator和EntryIterator,基类为HashIterator  
  10.     //基类为HashIterator  
  11.     private abstract class HashIterator<E> implements Iterator<E> {  
  12.         Entry<K,V> next;  // 散列表的链表的下一个Entry对象  
  13.         int expectedModCount;   // 与modCount同步的变量  
  14.         int index;      // 散列表的数组索引  
  15.         Entry<K,V> current;   // 散列表的链表的当前Entry对象  
  16.         //构造函数  
  17.         HashIterator() {  
  18.         //同步expectedModCount  
  19.             expectedModCount = modCount;  
  20.             if (size > 0) {   
  21.         //取得散列表的数组  
  22.                 Entry[] t = table;  
  23.         //取得取得散列表的数组中不为空的项目索引并将数组中的链表头赋值给next  
  24.                 while (index < t.length && (next = t[index++]) == null)  
  25.                     ;  
  26.             }  
  27.         }  
  28.     //虽然没看到对HashMap的方法调用,但是在构造函数中已经和HashMap对象通信  
  29.         public final boolean hasNext() {  
  30.             return next != null;  
  31.         }  
  32.     //通过分别遍历散列表中的当前链表和数组,查找下一个Entry对象  
  33.         final Entry<K,V> nextEntry() {  
  34.         //检查迭代器运行期间,容器结构是否修改,如修改则报错  
  35.             if (modCount != expectedModCount)  
  36.                 throw new ConcurrentModificationException();  
  37.         //取得遍历散列表中的当前链表  
  38.             Entry<K,V> e = next;  
  39.             if (e == null)  
  40.                 throw new NoSuchElementException();  
  41.         //如果当前链表遍历到尾,则继续对数组进行遍历  
  42.             if ((next = e.next) == null) {  
  43.                 Entry[] t = table;  
  44.                 while (index < t.length && (next = t[index++]) == null)  
  45.                     ;  
  46.             }  
  47.         //取得最新的链表  
  48.         current = e;  
  49.         //返回Entry对象  
  50.             return e;  
  51.         }  
  52.     //使用了HashMap对象的removeEntryForKey进行删除操作,又是隐藏细节。。。  
  53.         public void remove() {  
  54.             if (current == null)  
  55.                 throw new IllegalStateException();  
  56.             if (modCount != expectedModCount)  
  57.                 throw new ConcurrentModificationException();  
  58.             Object k = current.key;  
  59.             current = null;  
  60.             HashMap.this.removeEntryForKey(k);  
  61.             expectedModCount = modCount;  
  62.         }  
  63.     }  
  64.     //迭代器的具体实现类ValueIterator,继承自HashIterator  
  65.     private final class ValueIterator extends HashIterator<V> {  
  66.     //实现next方法,返回Entry对象的Value  
  67.         public V next() {  
  68.             return nextEntry().value;  
  69.         }  
  70.     }  
  71.     //迭代器的具体实现类KeyIterator,继承自HashIterator  
  72.     private final class KeyIterator extends HashIterator<K> {  
  73.     //实现next方法,返回Entry对象的Key  
  74.         public K next() {  
  75.             return nextEntry().getKey();  
  76.         }  
  77.     }  
  78.     //迭代器的具体实现类EntryIterator,继承自HashIterator  
  79.     private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {  
  80.     //实现next方法,返回Entry对象  
  81.         public Map.Entry<K,V> next() {  
  82.             return nextEntry();  
  83.         }  
  84.     }  
  85.     //三个工厂方法分别制造三个不同的迭代器  
  86.     Iterator<K> newKeyIterator()   {  
  87.         return new KeyIterator();  
  88.     }  
  89.     Iterator<V> newValueIterator()   {  
  90.         return new ValueIterator();  
  91.     }  
  92.     Iterator<Map.Entry<K,V>> newEntryIterator()   {  
  93.         return new EntryIterator();  
  94.     }  
  95.     //因上面三个迭代器为HashMap专用,所以不适合Set(ValueIterator和EntryIterator),所以在HashMap的内部类KeySet中又使用了HashMap的KeyIterator,所以HashSet的具体迭代器其实就是HashMap的KeyIterator迭代器  
  96.     private final class KeySet extends AbstractSet<K> {  
  97.         public Iterator<K> iterator() {  
  98.             return newKeyIterator();  
  99.         }  
  100.         public int size() {  
  101.             return size;  
  102.         }  
  103.         public boolean contains(Object o) {  
  104.             return containsKey(o);  
  105.         }  
  106.         public boolean remove(Object o) {  
  107.             return HashMap.this.removeEntryForKey(o) != null;  
  108.         }  
  109.         public void clear() {  
  110.             HashMap.this.clear();  
  111.         }  
  112.     }  
  113.     private transient Set<Map.Entry<K,V>> entrySet = null;  
  114.     public Set<K> keySet() {  
  115.         Set<K> ks = keySet;  
  116.         return (ks != null ? ks : (keySet = new KeySet()));  
  117.     }  
  118. }  

  TreeSet的迭代器实现和HashMap很相似,在这里就不再罗嗦了,有兴趣的读者可以去研读一下源码。

      对于再下层的实现类,可以灵活的重写生产方法,并实现专用的迭代器内部类。

  三、 总结

  从代码我们可以得出以下几点:

      1.具体容器角色和具体迭代器角色因为是紧耦合关系,在具体容器中使用内部类将具体迭代器实现是一个很好的做法,方便了具体迭代器直接访问具体容器的所有细节。

      2.内部类为私有,既实现类具体迭代器,又使此容器的专用迭代器对外不可见,迫使使用者进行接口编程。

          3.使用迭代器访问一个容器对象的内容而无需暴露它的内部表示。

          4.对同一个容器对象,可以同时进行多个遍历。

          5.支持以不同的方式遍历一个容器角色。根据实现方式的不同,效果上会有差别。

          6.简化了容器的接口。但是在java Collection中为了提高可扩展性,容器还是提供了遍历的接口。

          7.为遍历不同的容器结构提供一个统一的接口。