一、迭代器概述
1、什么是迭代器?
在Java中,有很多的數據容器,對於這些的操作有很多的共性。Java采用了迭代器來為各種容器提供了公共的操作接口。這樣使得對容器的遍歷操作與其具體的底層實現相隔離,達到解耦的效果。
在Iterator接口中定義了三個方法:
2、迭代器使用
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()); } }
執行結果:
二、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中,有三個變量分別是
cursor:表示下一個元素的索引位置
lastRet:表示上一個元素的索引位置
expectModCount:預期被修改的次數
下面看一下Itr類實現了Iterator接口的三個方法:
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,使之保持統一。
三、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); }