zoukankan      html  css  js  c++  java
  • Java学习之Iterator(迭代器)的一般用法

     

    一、迭代器概述

      1、什么是迭代器?

      在Java中,有很多的数据容器,对于这些的操作有很多的共性。Java采用了迭代器来为各种容器提供了公共的操作接口。这样使得对容器的遍历操作与其具体的底层实现相隔离,达到解耦的效果。

      在Iterator接口中定义了三个方法:

      

      2、迭代器使用

        public static void main(String[] args)
        {
            List<String> list=new ArrayList<>();
            list.add("abc");
            list.add("edf");
            list.add("ghi");
            for(Iterator<String> it=list.iterator();it.hasNext();)
            {
                System.out.println(it.next());
            }
        }

     执行结果: 

    二、ArrayList的Iterator实现

       private class Itr implements Iterator<E> 
      { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; ... }

      在ArrayList内部定义了一个内部类Itr,该类实现了Iterator接口。

      在Itr中,有三个变量分别是

      cursor:表示下一个元素的索引位置

      lastRet:表示上一个元素的索引位置

      expectModCount:预期被修改的次数

      下面看一下Itr类实现了Iterator接口的三个方法:

     public boolean hasNext() 
     {
         return cursor != size;//当cursor不等于size时,表示仍有索引元素
     }
         public E next() //返回下一个元素
        {
                checkForComodification();
                int i = cursor;
                if (i >= size)
                    throw new NoSuchElementException();
                Object[] elementData = ArrayList.this.elementData;
                if (i >= elementData.length)
                    throw new ConcurrentModificationException();
                cursor = i + 1;
                return (E) elementData[lastRet = i];
        }

      在next()方法中有一个checkForComodification()方法,其实现为:

        final void checkForComodification() 
        {
             if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }

      可以看到,该函数是用来判断集合的修改次数是否合法。

      在集合内部维护一个字段modCount用于记录集合被修改的次数,每当集合内部结构发生变化(add,remove,set)时,modCount+1。

      在迭代器内部也维护一个字段expectedModCount,同样记录当前集合修改的次数,初始化为集合的modCount值。当我们在调用Iterator进行遍历操作时,如果有其他线程修改list会出现modCount!=expectedModCount的情况,就会报并发修改异常java.util.ConcurrentModificationException。下面为示例代码:

       public static void main(String[] args)
        {
             ArrayList<String> aList=new ArrayList<String>();
             aList.add("bbc");
             aList.add("abc");
             aList.add("ysc");
             aList.add("saa");
             System.out.println("移除前:"+aList);
       
             Iterator<String> it=aList.iterator();
             while(it.hasNext())
             {
                 if("abc".equals(it.next()))
                 {
                    aList.remove("abc");          
                 }
             }
             System.out.println("移除后:"+aList);
      }            

      

      上面的代码中,如果我们只使用迭代器来进行删除,则不会出现并发修改异常错误。

      public static void main(String[] args)
        {
           ArrayList<String> aList=new ArrayList<String>();
             aList.add("bbc");
             aList.add("abc");
             aList.add("ysc");
             aList.add("saa");
             System.out.println("移除前:"+aList);
             
             Iterator<String> it=aList.iterator();
             while(it.hasNext())
             {
                if("abc".equals(it.next()))
                {
                  it.remove();
                }
             }
             System.out.println("移除后:"+aList);
      }

      

         public void remove()
         {
                if (lastRet < 0)
                    throw new IllegalStateException();
                checkForComodification();
                try {
                    ArrayList.this.remove(lastRet);
                    cursor = lastRet;
                    lastRet = -1;
                    expectedModCount = modCount;
                } catch (IndexOutOfBoundsException ex) {
                    throw new ConcurrentModificationException();
                }
         }

      在执行remove操作时,同样先执行checkForComodification(),然后会执行ArrayList的remove()方法,该方法会将modCount值加1,这里我们将expectedModCount=modCount,使之保持统一。

    三、ListIterator

      上面可以看到,Iterator只提供了删除元素的方法remove,如果我们想要在遍历的时候添加元素怎么办?

      ListIterator接口继承了Iterator接口,它允许程序员按照任一方向遍历列表,迭代期间修改列表,并获得迭代器在列表中的当前位置。

      ListIterator接口定义了下面几个方法:

      

      下面使用ListIterator来对list进行边遍历边添加元素操作:

        public static void main(String[] args)
        {
            ArrayList<String> aList = new ArrayList<String>();
            aList.add("bbc");
            aList.add("abc");
            aList.add("ysc");
            aList.add("saa");
            System.out.println("移除前:" + aList);
            ListIterator<String> listIt = aList.listIterator();
            while (listIt.hasNext())
            {
                if ("abc".equals(listIt.next()))
                {
                    listIt.add("haha");
                }
            }
            System.out.println("移除后:" + aList);
        }

      

    =============================================

    迭代器(Iterator)

      迭代器是一种设计模式,它是一个对象,它可以遍历并选择序列中的对象,而开发人员不需要了解该序列的底层结构。迭代器通常被称为“轻量级”对象,因为创建它的代价小。

      Java中的Iterator功能比较简单,并且只能单向移动:

      (1) 使用方法iterator()要求容器返回一个Iterator。第一次调用Iterator的next()方法时,它返回序列的第一个元素。注意:iterator()方法是java.lang.Iterable接口,被Collection继承。

      (2) 使用next()获得序列中的下一个元素。

      (3) 使用hasNext()检查序列中是否还有元素。

      (4) 使用remove()将迭代器新返回的元素删除。

      Iterator是Java迭代器最简单的实现,为List设计的ListIterator具有更多的功能,它可以从两个方向遍历List,也可以从List中插入和删除元素。

    迭代器应用:
     list l = new ArrayList();
     l.add("aa");
     l.add("bb");
     l.add("cc");
     for (Iterator iter = l.iterator(); iter.hasNext();) {
      String str = (String)iter.next();
      System.out.println(str);
     }
     /*迭代器用于while循环
     Iterator iter = l.iterator();
     while(iter.hasNext()){
      String str = (String) iter.next();
      System.out.println(str);
     }
     */

    =========================================================

    Java迭代器深入理解及使用

    转载 2015年08月22日 01:21:42
     

    Iterator(迭代器)

                作为一种设计模式,迭代器可以用于遍历一个对象,对于这个对象的底层结构开发人员不必去了解。

           java中的Iterator一般称为“轻量级”对象,创建它的代价是比较小的。这里笔者不会去考究迭代器这种

           设计模式,仅在JDK代码层面上谈谈迭代器的时候以及使用迭代器的好处。

    Iterator详解

                Iterator是作为一个接口存在的,它定义了迭代器所具有的功能。这里我们就以Iterator接口来看,不考

           虑起子类ListIterator。其源码如下:      

     

    1. package java.util;    
    2. public interface Iterator<E> {    
    3.     boolean hasNext();    
    4.     E next();    
    5.     void remove();    
    6. }    


                对于这三个方法所实现的功能,字面意义就是了。不过貌似对迭代器的工作“过程”还是迷雾,接下来

     

             我们以一个实际例子来看。

     

    1. List<String> list = new ArrayList<String>();    
    2.         list.add("TEST1");    
    3.         list.add("TEST2");    
    4.         list.add("TEST3");    
    5.         list.add("TEST4");    
    6.         list.add("TEST6");    
    7.         list.add("TEST5");    
    8.         Iterator<String> it = list.iterator();     
    9.         while(it.hasNext())    
    10.         {    
    11.             System.out.println(it.next());    
    12.         }    


                    这段代码的输出结果不用多说,这里的it更像是“游标”,不过这游标具体做了啥,我们还得通过

     

               list.iterator()好好看看。通过源码了解到该方法产生了一个实现Iterator接口的对象。

     

    1. private class Itr implements Iterator<E> {    
    2.           
    3.        int cursor = 0;    
    4.        int lastRet = -1;    
    5.        int expectedModCount = modCount;    
    6.        public boolean hasNext() {    
    7.            return cursor != size();    
    8.        }    
    9.     
    10.        public E next() {    
    11.            checkForComodification();    
    12.            try {    
    13.                int i = cursor;    
    14.                E next = get(i);    
    15.                lastRet = i;    
    16.                cursor = i + 1;    
    17.                return next;    
    18.            } catch (IndexOutOfBoundsException e) {    
    19.                checkForComodification();    
    20.                throw new NoSuchElementException();    
    21.            }    
    22.        }    
    23.     
    24.        public void remove() {    
    25.            if (lastRet < 0)    
    26.                throw new IllegalStateException();    
    27.            checkForComodification();    
    28.     
    29.            try {    
    30.                AbstractList.this.remove(lastRet);    
    31.                if (lastRet < cursor)    
    32.                    cursor--;    
    33.                lastRet = -1;    
    34.                expectedModCount = modCount;    
    35.            } catch (IndexOutOfBoundsException e) {    
    36.                throw new ConcurrentModificationException();    
    37.            }    
    38.        }    
    39.     
    40.        final void checkForComodification() {    
    41.            if (modCount != expectedModCount)    
    42.                throw new ConcurrentModificationException();    
    43.        }    
    44.    }    


                         对于上述的代码不难看懂,有点疑惑的是int expectedModCount = modCount;这句代码

     

                 其实这是集合迭代中的一种“快速失败”机制,这种机制提供迭代过程中集合的安全性。阅读源码

                 就可以知道ArrayList中存在modCount对象,增删操作都会使modCount++,通过两者的对比

                 迭代器可以快速的知道迭代过程中是否存在list.add()类似的操作,存在的话快速失败!

                         以一个实际的例子来看,简单的修改下上述代码。        

     

    1. while(it.hasNext())    
    2.         {    
    3.             System.out.println(it.next());    
    4.             list.add("test");    
    5.         }    


                          这就会抛出一个下面的异常,迭代终止。

     

              

                           对于快速失败机制以前文章中有总结,现摘录过来:    

    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的类

     

    1. package com.iterator;    
    2.     
    3. import java.util.Iterator;    
    4.     
    5. public class MyIterable implements Iterable<String> {    
    6.     protected String[] words = ("And that is how "    
    7.            + "we know the Earth to be banana-shaped.").split(" ");    
    8.      
    9.     public Iterator<String> iterator() {    
    10.        return new Iterator<String>() {    
    11.            private int index = 0;    
    12.      
    13.            public boolean hasNext() {    
    14.               return index < words.length;    
    15.            }    
    16.      
    17.            public String next() {    
    18.               return words[index++];    
    19.            }    
    20.      
    21.            public void remove() {}    
    22.        };    
    23.     }    
    24.        
    25.     public static void main(String[] args){    
    26.        for(String s:new MyIterable())    
    27.            System.out.print(s+",");    
    28.     }   

       输出结果如下:

     

                      And,that,is,how,we,know,the,Earth,to,be,banana-shaped.,

  • 相关阅读:
    Go 学习之旅
    IdentityServer4 3.1.x 迁移到 4.x
    Redash 二开
    frp 内网穿透远程桌面(Windows 10)配置
    Redash 二开
    Redash 二开
    Nginx 强制 HTTPS 配置
    ASP.NET Core 奇淫技巧之SPA部署
    .NET Core 对接微信小程序数据解密
    19c生产enq: FB
  • 原文地址:https://www.cnblogs.com/aipan/p/7514001.html
Copyright © 2011-2022 走看看