Java中Iterator(迭代器)實現原理


“這兩天正好學到了Java迭代器這塊兒,一開始我以為是類似於指針的原理,但是后面的操作讓我覺得和指針又差太多,查了資料看了下迭代器的原理,如下:”

 

迭代器是一種設計模式,它是一個對象,它可以遍歷並選擇序列中的對象,而開發人員不需要了解該序列的底層結構。迭代器通常被稱為“輕量級”對象,因為創建它的代價小。

  Java中的Iterator功能比較簡單,並且只能單向移動:

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

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

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

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

看一下它的工作原理:

1.public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> { // List接口實現了Collection<E>, Iterable<E> 
2.  
3.    protected AbstractList() {  
4.    }  
5.    
6.    ...  
7.  
8.    public Iterator<E> iterator() {  
9.    return new Itr();  // 這里返回一個迭代器
10.    }  
11.  
12.    private class Itr implements Iterator<E> {  // 內部類Itr實現迭代器
13.       
14.    int cursor = 0;  
15.    int lastRet = -1;  
16.    int expectedModCount = modCount;  
17.  
18.    public boolean hasNext() {  // 實現hasNext方法
19.            return cursor != size();  
20.    }  
21.  
22.    public E next() {  // 實現next方法
23.            checkForComodification();  
24.        try {  
25.        E next = get(cursor);  
26.        lastRet = cursor++;  
27.        return next;  
28.        } catch (IndexOutOfBoundsException e) {  
29.        checkForComodification();  
30.        throw new NoSuchElementException();  
31.        }  
32.    }  
33.  
34.    public void remove() {  // 實現remove方法
35.        if (lastRet == -1)  
36.        throw new IllegalStateException();  
37.            checkForComodification();  
38.  
39.        try {  
40.        AbstractList.this.remove(lastRet);  
41.        if (lastRet < cursor)  
42.            cursor--;  
43.        lastRet = -1;  
44.        expectedModCount = modCount;  
45.        } catch (IndexOutOfBoundsException e) {  
46.        throw new ConcurrentModificationException();  
47.        }  
48.    }  
49.  
50.    final void checkForComodification() {  
51.        if (modCount != expectedModCount)  
52.        throw new ConcurrentModificationException();  
53.    }  
54.    }  
55.}

  

可以看到,實現next()是通過get(cursor),然后cursor++,相當於c++里面設置一個flag標志位,因為迭代是單方面的,所以它只能進行corsor++操作,在python里cursor稱為游標,

也是起到一個標志的作用。

迭代部分的代碼很簡單,唯一難懂的是remove操作里涉及到的expectedModCount = modCount;

在網上查到說這是集合迭代中的一種“快速失敗”機制,這種機制提供迭代過程中集合的安全性。

從源代碼里可以看到增刪操作都會使modCount++,通過和expectedModCount的對比,迭代器可以快速的知道迭代過程中是否存在list.add()類似的操作,存在的話快速失敗!
 
就是說在迭代的過程中不允許進行add()類似的操作,如果有就會拋出異常。
 
關於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.
 
也就是說,modCount記錄修改此列表的次數:包括 改變列表的結構,改變列表的大小,打亂列表的順序等使正在進行迭代產生錯誤的結果。
 
Tips:僅僅設置元素的值並不是結構的修改
 
我們知道的是ArrayList是線程不安全的,如果在使用迭代器的過程中有其他的線程修改了List就會拋出ConcurrentModificationException,這就是 Fail-Fast機制。
 
順便說一下迭代器ListIter的方法:
  • ListIter<Integer>  ListIter = al.listItertor();    //創建數組列表al的迭代器ListIter
  • listIter.add(new Integer(x));                        //在序號為0的元素前添加一個元素x,因為創建al的迭代器的時候,游標cursor是標志的第一個元素,也就是序號為0的元素
  • listIter.hasNext();                                       // 原理就是判斷cursor++后的值是否為空
  • listIter.set(new Integer(x));                        //把游標cursor指向的數替換為x;
  • listIter.next()                                             //cursor++
  • listIter.previous()                                     //用來反向遍歷可,先把游標cursor定位到最后,listIter = al.listitertor(al.size());
 
參考鏈接:https://www.cnblogs.com/xiongmozhou/p/10085105.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM