java迭代器

Iterator(迭代器)
            作为一种设计模式,迭代器可以用于遍历一个对象,对于这个对象的底层结构开发人员不必去了解。
 
       java中的Iterator一般称为“轻量级”对象,创建它的代价是比较小的。这里笔者不会去考究迭代器这种
 
       设计模式,仅在JDK代码层面上谈谈迭代器的时候以及使用迭代器的好处。
 
Iterator详解
            Iterator是作为一个接口存在的,它定义了迭代器所具有的功能。这里我们就以Iterator接口来看,不考
 
       虑起子类ListIterator。其 源码如下:      
 
[java] 
package java.util;  
public interface Iterator<E> {  
    boolean hasNext();  
    E next();  
    void remove();  
}  
            对于这三个方法所实现的功能,字面意义就是了。不过貌似对迭代器的工作“过程”还是迷雾,接下来
         我们以一个实际例子来看。
[java] view plaincopy
List<String> list = new ArrayList<String>();  
        list.add("TEST1");  
        list.add("TEST2");  
        list.add("TEST3");  
        list.add("TEST4");  
        list.add("TEST6");  
        list.add("TEST5");  
        Iterator<String> it = list.iterator();   
        while(it.hasNext())  
        {  
            System.out.println(it.next());  
        }  
                这段代码的输出结果不用多说,这里的it更像是“游标”,不过这游标具体做了啥,我们还得通过
           list.iterator()好好看看。通过源码了解到该方法产生了一个实现Iterator接口的对象。
 
[java]  
private class Itr implements Iterator<E> {  
        
       int cursor = 0;  
       int lastRet = -1;  
       int expectedModCount = modCount;  
       public boolean hasNext() {  
           return cursor != size();  
       }  
  
       public E next() {  
           checkForComodification();  
           try {  
               int i = cursor;  
               E next = get(i);  
               lastRet = i;  
               cursor = i + 1;  
               return next;  
           } catch (IndexOutOfBoundsException e) {  
               checkForComodification();  
               throw new NoSuchElementException();  
           }  
       }  
  
       public void remove() {  
           if (lastRet < 0)  
               throw new IllegalStateException();  
           checkForComodification();  
  
           try {  
               AbstractList.this.remove(lastRet);  
               if (lastRet < cursor)  
                   cursor--;  
               lastRet = -1;  
               expectedModCount = modCount;  
           } catch (IndexOutOfBoundsException e) {  
               throw new ConcurrentModificationException();  
           }  
       }  
  
       final void checkForComodification() {  
           if (modCount != expectedModCount)  
               throw new ConcurrentModificationException();  
       }  
   }  
                     对于上述的代码不难看懂,有点疑惑的是int expectedModCount = modCount;这句代码
             其实这是集合迭代中的一种“快速失败”机制,这种机制提供迭代过程中集合的安全性。 阅读源码
 
             就可以知道ArrayList中存在modCount对象,增删操作都会使modCount++,通过两者的对比
 
             迭代器可以快速的知道迭代过程中是否存在list.add()类似的操作,存在的话快速失败!
 
                     以一个实际的例子来看,简单的修改下上述代码。        
 
[java] 
while(it.hasNext())  
        {  
            System.out.println(it.next());  
            list.add("test");  
        }  
                      这就会抛出一个下面的异常,迭代终止。
          
 
                       对于快速失败机制以前文章中有总结,现摘录过来:    
 
Fail-Fast(快速失败)机制
                     仔细观察上述的各个方法,我们在源码中就会发现一个特别的属性modCount,API解释如下:
 
            The number of times this list has been structurally modified. Structural modifications are those
 
             that change the size of the list, or otherwise perturb it in such a fashion that iterations in progress
 
             may yield incorrect results.
 
              记录修改此列表的次数:包括改变列表的结构,改变列表的大小,打乱列表的顺序等使正在进行
 
          迭代产生错误的结果。Tips:仅仅设置元素的值并不是结构的修改
 
              我们知道的是ArrayList是线程不安全的,如果在使用迭代器的过程中有其他的线程修改了List就会
 
             抛出ConcurrentModificationException这就是Fail-Fast机制。   
 
                 那么快速失败究竟是个什么意思呢?
 
          在ArrayList类创建迭代器之后,除非通过迭代器自身remove或add对列表结构进行修改,否则在其他
 
          线程中以任何形式对列表进行修改,迭代器马上会抛出异常,快速失败。 
 
迭代器的好处
           通过上述我们明白了迭代是到底是个什么,迭代器的使用也十分的简单。现在简要的总结下使用迭代
 
       器的好处吧。
 
                1、迭代器可以提供统一的迭代方式。
 
                2、迭代器也可以在对客户端透明的情况下,提供各种不同的迭代方式。
 
                3、迭代器提供一种快速失败机制,防止多线程下迭代的不安全操作。
 
           不过对于第三点尚需注意的是:就像上述事例代码一样,我们不能保证迭代过程中出现“快速
 
         失败”的都是因为同步造成的,因此为了保证迭代操作的正确性而去依赖此类异常是错误的!
 
 foreach循环
           通过阅读源码我们还发现一个Iterable接口。它包含了一个产生Iterator对象的iterator()方法,
 
       而且将Iterator对象呗foreach用来在序列中移动。对于任何实现Iterable接口的对象都可以使用
 
       foreach循环。
 
           foreach语法的冒号后面可以有两种类型:一种是数组,另一种是是实现了Iterable接口的类
 
        对于数组不做讨论,我们看看实现了Iterable的类
[java]  
package com.iterator;  
  
import java.util.Iterator;  
  
public class MyIterable implements Iterable<String> {  
    protected String[] words = ("And that is how "  
           + "we know the Earth to be banana-shaped.").split(" ");  
   
    public Iterator<String> iterator() {  
       return new Iterator<String>() {  
           private int index = 0;  
   
           public boolean hasNext() {  
              return index < words.length;  
           }  
   
           public String next() {  
              return words[index++];  
           }  
   
           public void remove() {}  
       };  
    }  
     
    public static void main(String[] args){  
       for(String s:new MyIterable())  
           System.out.print(s+",");  
    }  
}  
                  输出结果如下:
                  And,that,is,how,we,know,the,Earth,to,be,banana-shaped.,


迭代器是一种模式,它可以使得对于序列类型的数据结构的遍历行为与被遍历的对象分离,即我们无需关心该序列的底层结构是什么样子的。只要拿到这个对象,使用迭代器就可以遍历这个对象的内部.

1.Iterator

Java提供一个专门的迭代器<<interface>>Iterator,我们可以对某个序列实现该interface,来提供标准的Java迭代器。Iterator接口实现后的功能是“使用”一个迭代器.

文档定义:

[java]  view plain copy print ?
  1. Package java.util;

  2. publicinterface Iterator<E> {

  3. boolean hasNext();//判断是否存在下一个对象元素

  4. E next();

  5. void remove();
  6. }
[java]  view plain  copy
 print ?
  1. <span style="font-size:18px;">Package  java.util;   
  2.   
  3. public interface Iterator<E> {  
  4.   
  5.     boolean hasNext();//判断是否存在下一个对象元素  
  6.   
  7.      E next();  
  8.   
  9.     void remove();  
  10. }  
  11. </span>  


2.Iterable

Java中还提供了一个Iterable接口,Iterable接口实现后的功能是“返回”一个迭代器,我们常用的实现了该接口的子接口有: Collection<E>, Deque<E>, List<E>, Queue<E>, Set<E> 等.该接口的iterator()方法返回一个标准的Iterator实现。实现这个接口允许对象成为 Foreach 语句的目标。就可以通过Foreach语法遍历你的底层序列。

Iterable接口包含一个能够产生Iterator的iterator()方法,并且Iterable接口被foreach用来在序列中移动。因此如果创建了任何实现Iterable接口的类,都可以将它用于foreach语句中。

[java]  view plain copy print ?
  1. 文档定义:

  2. Package java.lang;

  3. import java.util.Iterator;
  4. public interface Iterable<T> {
  5. Iterator<T> iterator();
  6. }
[java]  view plain  copy
 print ?
  1. <span style="font-size:18px;">文档定义:  
  2.   
  3. Package  java.lang;   
  4.   
  5. import  java.util.Iterator;   
  6. public interface Iterable<T> {   
  7.      Iterator<T> iterator();   
  8. }  
  9.   
  10. </span>  


[java]  view plain copy print ?
  1. 使用Iterator的简单例子

  2. import java.util.*;

  3. publicclass TestIterator {


  4. public static void main(String[] args) {



  5. List list=new ArrayList();

  6. Map map=new HashMap();

  7. for(int i=0;i<10;i++){

  8. list.add(new String("list"+i) );

  9. map.put(i, new String("map"+i));

  10. }

  11. Iterator iterList= list.iterator();//List接口实现了Iterable接口

  12. while(iterList.hasNext()){

  13. String strList=(String)iterList.next();

  14. System.out.println(strList.toString());

  15. }

  16. Iterator iterMap=map.entrySet().iterator();

  17. while(iterMap.hasNext()){

  18. Map.Entry strMap=(Map.Entry)iterMap.next();

  19. System.out.println(strMap.getValue());



  20. }

  21. }

  22. }

  23. <span style="color: rgb(0, 0, 153); font-size: 18px;"> </span><span style="color: rgb(0, 0, 153); font-size: 18px;"></span>
[java]  view plain  copy
 print ?
  1. <span style="font-size:18px;">使用Iterator的简单例子  
  2.   
  3. import java.util.*;  
  4.   
  5. public class TestIterator {  
  6.   
  7.   
  8.    public static void main(String[] args) {  
  9.   
  10.           
  11.   
  12.       List list=new ArrayList();  
  13.   
  14.       Map map=new HashMap();  
  15.   
  16.       for(int i=0;i<10;i++){  
  17.   
  18.           list.add(new String("list"+i) );  
  19.   
  20.           map.put(i, new String("map"+i));  
  21.   
  22.       }  
  23.   
  24.       Iterator iterList= list.iterator();//List接口实现了Iterable接口  
  25.   
  26.         while(iterList.hasNext()){  
  27.   
  28.           String strList=(String)iterList.next();  
  29.   
  30.           System.out.println(strList.toString());  
  31.   
  32.       }  
  33.   
  34.       Iterator iterMap=map.entrySet().iterator();  
  35.   
  36.       while(iterMap.hasNext()){  
  37.   
  38.           Map.Entry  strMap=(Map.Entry)iterMap.next();  
  39.   
  40.           System.out.println(strMap.getValue());  
  41.   
  42.    
  43.   
  44.       }  
  45.   
  46.    }  
  47.   
  48. }  
  49.   
  50.  <span style="color:#0099;">  </span><span style="color:#0099;"></span> </span>  

接口Iterator在不同的子接口中会根据情况进行功能的扩展,例如针对List的迭代器ListIterator,该迭代器只能用于各种List类的访问。ListIterator可以双向移动。添加了previous()等方法.

3 Iterator与泛型搭配

Iterator对集合类中的任何一个实现类,都可以返回这样一个Iterator对象。可以适用于任何一个类。

因为集合类(List和Set等)可以装入的对象的类型是不确定的,从集合中取出时都是Object类型,用时都需要进行强制转化,这样会很麻烦,用上泛型,就是提前告诉集合确定要装入集合的类型,这样就可以直接使用而不用显示类型转换.非常方便.

4.foreach和Iterator的关系

for each是jdk5.0新增加的一个循环结构,可以用来处理集合中的每个元素而不用考虑集合定下标。

格式如下 

for(variable:collection){ statement; }

定义一个变量用于暂存集合中的每一个元素,并执行相应的语句(块)。collection必须是一个数组或者是一个实现了lterable接口的类对象。 

[java]  view plain copy print ?
  1. 上面的例子使用泛型和forEach的写法:

  2. import java.util.*;
  3. public class TestIterator {



  4. public static void main(String[] args) {



  5. List<String> list=new ArrayList<String> ();

  6. for(int i=0;i<10;i++){

  7. list.add(new String("list"+i) );

  8. }

  9. for(String str:list){

  10. System.out.println(str);

  11. }

  12. }
[java]  view plain  copy
 print ?
  1. <span style="font-size:18px;">上面的例子使用泛型和forEach的写法:  
  2.   
  3. import java.util.*;  
  4. public class TestIterator {  
  5.   
  6.   
  7.   
  8.    public static void main(String[] args) {  
  9.   
  10.           
  11.   
  12.       List<String>  list=new ArrayList<String> ();  
  13.   
  14.       for(int i=0;i<10;i++){  
  15.   
  16.           list.add(new String("list"+i) );  
  17.   
  18.       }  
  19.   
  20.       for(String str:list){  
  21.   
  22.         System.out.println(str);  
  23.   
  24.       }    
  25.   
  26. }  
  27.   
  28. </span>  


可以看出,使用for each循环语句的优势在于更加简洁,更不容易出错,不必关心下标的起始值和终止值。

forEach不是关键字,关键字还是for,语句是由iterator实现的,他们最大的不同之处就在于remove()方法上。

一般调用删除和添加方法都是具体集合的方法,例如:

List list = new ArrayList(); list.add(...); list.remove(...);

但是,如果在循环的过程中调用集合的remove()方法,就会导致循环出错,因为循环过程中list.size()的大小变化了,就导致了错误。 所以,如果想在循环语句中删除集合中的某个元素,就要用迭代器iterator的remove()方法,因为它的remove()方法不仅会删除元素,还会维护一个标志,用来记录目前是不是可删除状态,例如,你不能连续两次调用它的remove()方法,调用之前至少有一次next()方法的调用。

forEach就是为了让用iterator循环访问的形式简单,写起来更方便。当然功能不太全,所以但如有删除操作,还是要用它原来的形式。

4 使用for循环与使用迭代器iterator的对比

效率上的各有有事

采用ArrayList对随机访问比较快,而for循环中的get()方法,采用的即是随机访问的方法,因此在ArrayList里,for循环较快

采用LinkedList则是顺序访问比较快,iterator中的next()方法,采用的即是顺序访问的方法,因此在LinkedList里,使用iterator较快

数据结构角度分析,for循环适合访问顺序结构,可以根据下标快速获取指定元素.而Iterator 适合访问链式结构,因为迭代器是通过next()和Pre()来定位的.可以访问没有顺序的集合.

而使用 Iterator 的好处在于可以使用相同方式去遍历集合中元素,而不用考虑集合类的内部实现(只要它实现了 java.lang.Iterable 接口),如果使用 Iterator 来遍历集合中元素,一旦不再使用 List 转而使用 Set 来组织数据,那遍历元素的代码不用做任何修改,如果使用 for 来遍历,那所有遍历此集合的算法都得做相应调整,因为List有序,Set无序,结构不同,他们的访问算法也不一样.





今天同事写了几行类似这样的代码:

1
2
3
4
5
6
7
8
9
10
11
12
public  static  void  main(String args[]) {
     List<String> famous =  new  ArrayList<String>();
     famous.add( "liudehua" );
     famous.add( "madehua" );
     famous.add( "liushishi" );
     famous.add( "tangwei" );
     for  (String s : famous) {
         if  (s.equals( "madehua" )) {
             famous.remove(s);
         }
     }
}

运行出异常:

Exception in thread "main" java.util.ConcurrentModificationException

at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)

at java.util.AbstractList$Itr.next(AbstractList.java:343)

at com.bes.Test.main(Test.java:15)

Java新手最容易犯的错误,对JAVA集合进行遍历删除时务必要用迭代器。切记。

其实对于如上for循环,运行过程中还是转换成了如下代码:

1
2
3
4
5
6
for (Iterator<String> it = famous.iterator();it.hasNext();){
          String s = it.next();
          if (s.equals( "madehua" )){
              famous.remove(s);
          }
      }

仍然采用的是迭代器,但删除操作却用了错误的方法。如将famous.remove(s)改成it.remove()

则运行正常,结果也无误。

当然如果改成:

1
2
3
4
5
6
for  ( int  i =  0 ; i < famous.size(); i++) {
             String s = famous.get(i);
             if  (s.equals( "madehua" )) {
                 famous.remove(s);
             }
         }

这种方法,也是可以完成功能,但一般也不这么写。

为什么用了迭代码器就不能采用famous.remove(s)操作? 这种因为ArrayList与Iterator混合使用时会导致各自的状态出现不一样,最终出现异常。

我们看一下ArrayList中的Iterator实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
private  class  Itr  implements  Iterator<E> {
    /**
     * Index of element to be returned by subsequent call to next.
     */
    int  cursor =  0 ;
    /**
     * Index of element returned by most recent call to next or
     * previous.  Reset to -1 if this element is deleted by a call
     * to remove.
     */
    int  lastRet = - 1 ;
    /**
     * The modCount value that the iterator believes that the backing
     * List should have.  If this expectation is violated, the iterator
     * has detected concurrent modification.
     */
    int  expectedModCount = modCount;
    public  boolean  hasNext() {
            return  cursor != size();
    }
    public  E next() {
            checkForComodification();
        try  {
        E next = get(cursor);
        lastRet = cursor++;
        return  next;
        catch  (IndexOutOfBoundsException e) {
        checkForComodification();
        throw  new  NoSuchElementException();
        }
    }
    public  void  remove() {
        if  (lastRet == - 1 )
        throw  new  IllegalStateException();
            checkForComodification();
        try  {
        AbstractList. this .remove(lastRet);
        if  (lastRet < cursor)
            cursor--;
        lastRet = - 1 ;
        expectedModCount = modCount;
        catch  (IndexOutOfBoundsException e) {
        throw  new  ConcurrentModificationException();
        }
    }
    final  void  checkForComodification() {
        if  (modCount != expectedModCount)
        throw  new  ConcurrentModificationException();
    }
    }

基本上ArrayList采用size属性来维护自已的状态,而Iterator采用cursor来来维护自已的状态。

当size出现变化时,cursor并不一定能够得到同步,除非这种变化是Iterator主动导致的。

从上面的代码可以看到当Iterator.remove方法导致ArrayList列表发生变化时,他会更新cursor来同步这一变化。但其他方式导致ArrayList变化,Iterator是无法感知的。ArrayList自然也不会主动通知Iterator们,那将是一个繁重的工作。Iterator到底还是做了努力:为了防止状态不一致可能引发的无法设想的后果,Iterator会经常做checkForComodification检查,以防有变。如果有变,则以异常抛出,所以就出现了上面的异常。



为什么一定要去实现Iterable这个接口呢? 为什么不直接实现Iterator接口呢?

看一下JDK中的集合类,比如List一族或者Set一族,
都是实现了Iterable接口,但并不直接实现Iterator接口。
仔细想一下这么做是有道理的。因为Iterator接口的核心方法next()或者hasNext()
依赖于迭代器的当前迭代位置的。
如果Collection直接实现Iterator接口,势必导致集合对象中包含当前迭代位置的数据(指针)。
当集合在不同方法间被传递时,由于当前迭代位置不可预置,那么next()方法的结果会变成不可预知。
除非再为Iterator接口添加一个reset()方法,用来重置当前迭代位置。
但即时这样,Collection也只能同时存在一个当前迭代位置。
而Iterable则不然,每次调用都会返回一个从头开始计数的迭代器。
多个迭代器是互不干扰的。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值