Java迭代器深入理解及使用
Iterator(迭代器)
作為一種設計模式,迭代器可以用於遍歷一個物件,對於這個物件的底層結構開發人員不必去了解。
java中的Iterator一般稱為“輕量級”物件,建立它的代價是比較小的。這裡筆者不會去考究迭代器這種
設計模式,僅在JDK程式碼層面上談談迭代器的時候以及使用迭代器的好處。
Iterator詳解
Iterator是作為一個介面存在的,它定義了迭代器所具有的功能。這裡我們就以Iterator介面來看,不考
慮起子類ListIterator。其原始碼如下:
對於這三個方法所實現的功能,字面意義就是了。不過貌似對迭代器的工作“過程”還是迷霧,接下來package java.util; public interface Iterator<E> { boolean hasNext(); E next(); void remove(); }
我們以一個實際例子來看。
這段程式碼的輸出結果不用多說,這裡的it更像是“遊標”,不過這遊標具體做了啥,我們還得通過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()); }
list.iterator()好好看看。通過原始碼瞭解到該方法產生了一個實現Iterator介面的物件。
對於上述的程式碼不難看懂,有點疑惑的是int expectedModCount = modCount;這句程式碼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(); } }
其實這是集合迭代中的一種“快速失敗”機制,這種機制提供迭代過程中集合的安全性。閱讀原始碼
就可以知道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.,