Java迭代器深入理解及使用

Iterator(迭代器)

            作爲一種設計模式,迭代器可以用於遍歷一個對象,對於這個對象的底層結構開發人員不必去了解

       java中的Iterator一般稱爲“輕量級”對象,創建它的代價是比較小的。這裏筆者不會去考究迭代器這種

       設計模式,僅在JDK代碼層面上談談迭代器的時候以及使用迭代器的好處。

Iterator詳解

            Iterator是作爲一個接口存在的,它定義了迭代器所具有的功能。這裏我們就以Iterator接口來看,不考

       慮起子類ListIterator。其源碼如下:      

package java.util;
public interface Iterator<E> {
    boolean hasNext();
    E next();
    void remove();
}
            對於這三個方法所實現的功能,字面意義就是了。不過貌似對迭代器的工作“過程”還是迷霧,接下來

         我們以一個實際例子來看。

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接口的對象。

 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()類似的操作,存在的話快速失敗!

                     以一個實際的例子來看,簡單的修改下上述代碼。        

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

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.,



發佈了178 篇原創文章 · 獲贊 42 · 訪問量 91萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章