Java集合Iterator迭代器的實現

1、迭代器概述

  一、什麼是迭代器?

  在Java中,有不少的數據容器,對於這些的操做有不少的共性。Java採用了迭代器來爲各類容器提供了公共的操做接口。這樣使得對容器的遍歷操做與其具體的底層實現相隔離,達到解耦的效果。java

  在Iterator接口中定義了三個方法:程序員

  

  二、迭代器使用

    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());
        }
    }

 執行結果: 併發

2、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中,有三個變量分別是this

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

  lastRet:表示上一個元素的索引位置線程

  expectModCount:預期被修改的次數code

  下面看一下Itr類實現了Iterator接口的三個方法:blog

 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,使之保持統一。

3、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);
    }

  

相關文章
相關標籤/搜索