Java基礎 -- 深刻理解迭代器

Java基礎 -- 持有對象(容器)已經詳細介紹到,集合(Collection)的種類有不少種,好比ArrayList、LinkedList、HashSet...。html

因爲集合的內部結構不一樣,不少時候可能不知道該怎樣去遍歷一個集合中的元素。因此爲了使對集合內元素的操做更爲簡單,Java引入了迭代器模式!
java

一 爲何使用迭代器

迭代器把訪問邏輯從不一樣類型的集合類型中抽取出來,從而避免向外部暴露集合的內部結構。編程

對於數組咱們使用的是下標來進行處理的:數組

1 int array[] = new int[3]; 2 for (int i = 0; i < array.length; i++) { 3  System.out.println(array[i]); 4 }

ArrayList的處理:安全

1 List<String> list = new ArrayList<String>(); 2 for(int i = 0 ; i < list.size() ; i++){ 3 String string = list.get(i); 4 }

對於這兩種方式,咱們老是都知道它的內部結構,訪問代碼和集合自己是緊密耦合的,沒法將訪問邏輯從集合類和客戶端代碼中分離出來。不一樣的集合會對應不一樣的遍歷方法,客戶端代碼沒法複用。在實際應用中如何將上面兩個集合整合是至關麻煩的。因此纔有Iterator,它老是用同一種邏輯來遍歷集合。使得客戶端自身不須要來維護集合的內部結構,全部的內部狀態都由Iterator來維護。客戶端不用直接和集合進行打交道,而是控制Iterator向它發送向前向後的指令,就能夠遍歷集合。this

二 迭代器的使用

迭代器一般被稱爲輕量級對象;建立它的代價小,所以,常常能夠看到對迭代器有些奇怪的限制,例如,Java的Iterator只能單向移動,這個Iterator只能用來:spa

  • 使用方法iterator()要求集合返回一個Iterator,Iterator將準備好返回集合的第一個元素;
  • 使用next()獲取集合中的下一個元素;
  • 使用hasNext()檢查集合中是否還存在元素;
  • 使用remove()將迭代器新近返回的元素刪除;

一、Iterator接口

爲了觀察它的工做方式,讓咱們來看一個例子:線程

import java.util.*; public class SimpleIteration { public static void main(String[] args) { //默認從小到大排序
        List<Person> pers = new ArrayList<Person>(); Person p1 = new Person("吳定會",50,true); pers.add(p1); Person p2 = new Person("沈豔霞",46,false); pers.add(p2); Person p3 = new Person("張三",17,true); pers.add(p3); Person p4 = new Person("李四",34,false); pers.add(p4); Iterator<Person> it = pers.iterator(); //檢查list中是否還有元素
        while(it.hasNext()) { //獲取list中下一個元素
            Person p = it.next(); System.out.print(p + "  "); } System.out.println(); it = pers.iterator(); for(int i=0;i<4;i++) { //獲取list中下一個元素
 it.next(); //將迭代器新近返回的元素刪除
 it.remove(); System.out.println(i + ":" + pers); } System.out.print(pers); } }

 輸出結果以下:code

吳定會-50-true  沈豔霞-46-false  張三-17-true  李四-34-false  
0:[沈豔霞-46-false, 張三-17-true, 李四-34-false]
1:[張三-17-true, 李四-34-false]
2:[李四-34-false]
3:[]
[]

如今考慮建立一個display()方法,它沒必要知曉集合的確切類型:htm

import java.util.*; public class CrossContainerIteration { public static void display(Iterator<Person> it) { while(it.hasNext()) { Person p = it.next(); System.out.print(p + " "); } System.out.println(); } public static void main(String[] args) { ArrayList<Person> pers = new ArrayList<Person>(); Person p1 = new Person("吳定會",50,true); pers.add(p1); Person p2 = new Person("沈豔霞",46,false); pers.add(p2); Person p3 = new Person("張三",17,true); pers.add(p3); Person p4 = new Person("李四",34,false); pers.add(p4); LinkedList<Person> persLL = new LinkedList<Person>(pers); HashSet<Person> persHS = new HashSet<Person>(pers); display(pers.iterator()); display(persLL.iterator()); display(persHS.iterator()); } }

 輸出:

吳定會-50-true 沈豔霞-46-false 張三-17-true 李四-34-false 
吳定會-50-true 沈豔霞-46-false 張三-17-true 李四-34-false 
張三-17-true 吳定會-50-true 沈豔霞-46-false 李四-34-false

 能夠看到display()方法不包含任何有關它所遍歷的集合的類型信息,而這也展現了Iterator的真正威力,可以將遍歷集合的操做與集合底層結構分離。正由於如此,咱們有時纔會說,迭代器統一了對集合的訪問方式。

二、ListIterator

ListIterator是一個更增強大的Iterator的子類型,它只能用於各類List類的訪問,儘管Iterator只能向前移動,可是ListIterator能夠雙向移動。它還能夠產生相對於迭代器在列表中指向的當前位置的前一個和後一個元素的索引,而且可使用set()方法替代它訪問過的最後一個元素。能夠經過調用listIterrator()方法產生一個指向List開始處的ListIterator,而且還能夠經過調用listIterator(n)方法建立一個一開始指向列表索引爲n的元素處的ListIterator。下面的示例演示了全部這些能力:

import java.util.*; public class ListIteration { public static void main(String[] args) { List<Person> pers = new ArrayList<Person>(); Person p1 = new Person("吳定會",50,true); pers.add(p1); Person p2 = new Person("沈豔霞",46,false); pers.add(p2); Person p3 = new Person("張三",17,true); pers.add(p3); Person p4 = new Person("李四",34,false); pers.add(p4); //從前向後遍歷
        ListIterator<Person> it = pers.listIterator(); while(it.hasNext()) { System.out.print(it.next() + " "); } System.out.println(); //從後向前遍歷
        while(it.hasPrevious()) { System.out.print(it.previous() + " "); } System.out.println(); System.out.println(pers); //建立一個開始指向第三個索引元素處的ListIterator
        it = pers.listIterator(3); while(it.hasNext()) { System.out.println(it.next()); //替換在列表中從位置3開始向前的全部Person對象 
 it.set(p1); } System.out.println(pers); } }

 輸出:

吳定會-50-true 沈豔霞-46-false 張三-17-true 李四-34-false 
李四-34-false 張三-17-true 沈豔霞-46-false 吳定會-50-true 
[吳定會-50-true, 沈豔霞-46-false, 張三-17-true, 李四-34-false]
李四-34-false
[吳定會-50-true, 沈豔霞-46-false, 張三-17-true, 吳定會-50-true]

三 迭代器的實現

一、下面讓咱們看看Java中的Iterator接口是如何實現的

在Java中Iterator爲一個接口,它只提供了迭代的基本規則。在JDK中它是這樣定義的:對Collection進行迭代的迭代器。迭代器取代了Java Collection Framework中的Enumeration。迭代器與枚舉有兩點不一樣:

  • 迭代器在迭代期間能夠從集合中移除元素。
  • 方法名獲得了改進,Enumeration的方法名稱都比較長。

其接口定義以下:

package java.util; public interface Iterator<E> { boolean hasNext();//判斷是否存在下一個對象元素
 E next();//獲取下一個元素

    void remove();//移除元素
}

二、Iterable

Java中還提供了一個Iterable接口,Iterable接口實現後的功能是返回一個迭代器,咱們經常使用的實現了該接口的子接口有:Collection<E>、List<E>、Set<E>等。該接口的iterator()方法返回一個標準的Iterator實現。實現Iterable接口容許對象成爲foreach語句的目標就能夠經過foreach語句來遍歷你的底層序列。

Iterable接口包含一個能產生Iterator對象的方法,而且Iterable被foreach用來在序列中移動。所以若是建立了實現Iterable接口的類,均可以將它用於foreach中。

Iterable接口的具體實現:

Package java.lang; import java.util.Iterator; public interface Iterable<T> { Iterator<T> iterator(); }

 使用迭代器遍歷集合:

public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("張三1"); list.add("張三2"); list.add("張三3"); list.add("張三4"); List<String> linkList = new LinkedList<String>(); linkList.add("link1"); linkList.add("link2"); linkList.add("link3"); linkList.add("link4"); Set<String> set = new HashSet<String>(); set.add("set1"); set.add("set2"); set.add("set3"); set.add("set4"); //使用迭代器遍歷ArrayList集合
        Iterator<String> listIt = list.iterator(); while(listIt.hasNext()){ System.out.println(listIt.next()); } //使用迭代器遍歷Set集合
        Iterator<String> setIt = set.iterator(); while(setIt.hasNext()){ System.out.println(listIt.next()); } //使用迭代器遍歷LinkedList集合
        Iterator<String> linkIt = linkList.iterator(); while(linkIt.hasNext()){ System.out.println(listIt.next()); } }

 使用foreach遍歷集合:

List<String> list = new ArrayList<String>();
        list.add("張三1");
        list.add("張三2");
        list.add("張三3");
        list.add("張三4");
        for (String string : list) {
            System.out.println(string);
        }

 能夠看出使用foreach遍歷集合的優點在於代碼更加的簡潔,更不容易出錯,不用關心下標的起始值和終止值。

三、Iterator遍歷時不能夠刪除集合中的元素問題

在使用Iterator的時候禁止對所遍歷的容器進行改變其大小結構的操做。例如: 在使用Iterator進行迭代時,若是對集合進行了add、remove操做就會出現ConcurrentModificationException異常。

List<String> list = new ArrayList<String>();
        list.add("張三1");
        list.add("張三2");
        list.add("張三3");
        list.add("張三4");
        
        //使用迭代器遍歷ArrayList集合
        Iterator<String> listIt = list.iterator();
        while(listIt.hasNext()){
            Object obj = listIt.next();
            if(obj.equals("張三3")){
                list.remove(obj);
            }
        }

由於在你迭代以前,迭代器已經被經過list.itertor()建立出來了,若是在迭代的過程當中,又對list進行了改變其容器大小的操做,那麼Java就會給出異常。由於此時Iterator對象已經沒法主動同步list作出的改變,Java會認爲你作出這樣的操做是線程不安全的,就會給出善意的提醒(拋出ConcurrentModificationException異常)

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; public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") 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]; } 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(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }

經過查看源碼發現原來檢查並拋出異常的是checkForComodification()方法。在ArrayList中modCount是當前集合的版本號,每次修改(增、刪)集合都會加1;expectedModCount是當前迭代器的版本號,在迭代器實例化時初始化爲modCount。咱們看到在checkForComodification()方法中就是在驗證modCount的值和expectedModCount的值是否相等,因此當你在調用了ArrayList.add()或者ArrayList.remove()時,只更新了modCount的狀態,而迭代器中的expectedModCount未同步,所以纔會致使再次調用Iterator.next()方法時拋出異常。可是爲何使用Iterator.remove()就沒有問題呢?經過源碼的第32行發現,在Iterator的remove()中同步了expectedModCount的值,因此當你下次再調用next()的時候,檢查不會拋出異常。

使用該機制的主要目的是爲了實現ArrayList中的快速失敗機制(fail-fast),在Java集合中較大一部分集合是存在快速失敗機制的。

快速失敗機制產生的條件:當多個線程對Collection進行操做時,若其中某一個線程經過Iterator遍歷集合時,該集合的內容被其餘線程所改變,則會拋出ConcurrentModificationException異常。

因此要保證在使用Iterator遍歷集合的時候不出錯誤,就應該保證在遍歷集合的過程當中不會對集合產生結構上的修改。

使用Foreach時對集合的結構進行修改會出現異常:

上面咱們說了實現了Iterable接口的類就能夠經過Foreach遍歷,那是由於foreach要依賴於Iterable接口返回的Iterator對象,因此從本質上來說,Foreach其實就是在使用迭代器,在使用foreach遍歷時對集合的結構進行修改,和在使用Iterator遍歷時對集合結構進行修改本質上是同樣的。因此一樣的也會拋出異常,執行快速失敗機制。

foreach是JDK1.5新增長的一個循環結構,foreach的出現是爲了簡化咱們遍歷集合的行爲。

for循環與迭代器的對比:

效率上各有各的優點:

  • ArrayList對隨機訪問比較快,而for循環中使用的get()方法,採用的便是隨機訪問的方法,所以在ArrayList裏for循環快。
  • LinkedList則是順序訪問比較快,Iterator中的next()方法採用的是順序訪問方法,所以在LinkedList裏使用Iterator較快。

參考文獻:

[1] Java編程思想

[2] 深刻理解Java中的迭代器(部分轉載)

相關文章
相關標籤/搜索