我們知道集合中的遍歷都是通過迭代(iterator)完成的。
也許有人說,不一定非要使用迭代,如:
List<String> list = new LinkedList<String>(); list.add("a"); list.add("b"); list.add("c"); for(int i=0;i<list.size();i++){ String item = list.get(i); System.out.println(item); }
這種方式對於基於鏈表實現的List來說,是比較耗性能的。
因為get(int i)方法包含了一個循環,而且這個循環就是迭代遍歷一次List,直到遇到第i個元素,才停止循環,返回第i個元素。對於數量小,遍歷不頻繁的List來說,開銷可以忽略。否則,開銷將不容忽視。
所以集合遍歷是使用迭代器Iterator來遍歷的:
List<String> list = new LinkedList<String>(); list.add("a"); list.add("b"); list.add("c"); //獲取集合的迭代器 Iterator<String> itor = list.iterator(); //集合的普通for循環 for(;itor.hasNext();){//相當於 while(itor.hasNext()) String item = itor.next(); System.out.println(item); }
對應的for-Each循環的例子:
List<String> list = new LinkedList<String>(); list.add("a"); list.add("b"); list.add("c"); for(String item:list){//for-Each System.out.println(item); }
可以看出,for-Each循環比普通for循環要簡潔很多。
我們回答上面的兩個問題:
-
- 編譯器是如何處理集合中的for-Each循環的?
public static void main(String args[]) { List list = new LinkedList(); list.add("aaa"); list.add("bbb"); for(String item:list) { if("bbb".equals(item)) list.add("ccc"); } } 反編譯上面代碼: public static void main(String args[]) { List list = new LinkedList(); list.add("aaa"); list.add("bbb"); for(Iterator iterator = list.iterator(); iterator.hasNext();) { String item = (String)iterator.next(); if("bbb".equals(item)) list.add("ccc"); } }
與數組類似,編譯器最終也就是將集合中的for-Each循環處理成集合的普通for循環。而集合的Collection接口通過擴展Iterable接口來提供iterator()方。
那么我們換一個角度,是不是只要實現 Iterable接口,提供iterator()方法,也可以使用 for-Each循環呢?
例子:
class MyList<T> implements Iterable<T>{ private ArrayList<T> list = new ArrayList<>(); public void addId(T id){ list.add(id); } public boolean removeId(T id){ return list.remove(id); } @Override public Iterator<T> iterator() {//擴展自Iterable接口 //為了簡單起見,就直接使用已有的迭代器 return list.iterator(); } public static void main(String[] args) { MyList<String> myList = new MyList<>(); myList.addId("666999"); myList.addId("973219"); //for-Each for(String item:myList){ System.out.println(item); } } }
編譯通過。
所以只要實現了Iterable接口的類,都可以使用for-Each循環來遍歷。
集合迭代的陷阱
集合循環遍歷時所使用的迭代器Iterator有一個要求:在迭代的過程中,除了使用迭代器(如:Iterator.remove()方法)對集合增刪元素外,是不允許直接對集合進行增刪操作。否則將會拋出 ConcurrentModificationException異常。
所以,由於集合的for-Each循環本質上使用的還是Iterator來迭代,因此也要注意這個陷阱。for-Each循環很隱蔽地使用了Iterator,導致程序員很容易忽略掉這個細節,所以一定要注意。
看下面的例子,for-Each循環中修改了集合。
public static void main(String[] args) { List<String> list = new LinkedList<>(); list.add("aaa"); list.add("bbb"); for (String item : list) {//for-Each if ("bbb".equals(item)) { list.add("ccc"); //直接操作list } } }
運行拋出異常.
上面僅僅是單線程下的情況,如果在 多線程 的環境中,線程是交替運行的(時間片輪轉調度)。這就意味着,如果有兩個線程A、B,線程A對集合使用Iterator迭代遍歷,線程B則對集合進行增刪操作。線程A、B一旦交替運行,就會出現在迭代的同時對集合增刪的效果,也會拋出異常。
解決辦法就是加鎖變成原子操作。
-
- 集合中的for-Each循環能代替集合的普通for循環嗎?
同樣也不能。
集合中的for-Each循環的局限性與數組的for-Each循環是一樣的。集合的for-Each循環是不能對集合進行增刪操作、也不能獲取索引。
而集合的普通for循環可以使用的迭代器提供了對集合的增刪方法(如:Iterator.remove,ListIterator.add()),獲取索引的方法(如:ListIterator.nextIndex()、ListIterator.previousIndex());
擴展:Iterator源碼分析
我們來分析一下Iterator源碼,主要看看為什么在集合迭代時,修改集合可能會拋出ConcurrentModificationException異常。以ArrayList中實現的Iterator為例。
先來看一下ArrayList.iterator()方法,如下:
public Iterator<E> iterator() { return new Itr(); }
iterator()方法直接創建了一個類Itr的對象。那就接着看 Itr類的定義吧!發現Itr其實是ArrayList的內部類,實現了 Iterator 接口。
/** * An optimized version of AbstractList.Itr */ 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(); //ArrayList的底層數組 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 expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } @Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> consumer) { Objects.requireNonNull(consumer); final int size = ArrayList.this.size; int i = cursor; if (i >= size) { return; } final Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) { throw new ConcurrentModificationException(); } while (i != size && modCount == expectedModCount) { consumer.accept((E) elementData[i++]); } // update once at end of iteration to reduce heap write traffic cursor = i; lastRet = i - 1; checkForComodification(); } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
ArrayList.this.elementData是ArrayList的底層數組,這些方法都是對ArrayList.this.elementData這個底層數組進行操作。
重點看一下checkForComodification()方法,它是用來拋出ConcurrentModificationException異常,判斷modCount與expectedModCount是否相等。modCount存儲的AarryList中的元素個數。而expectedModCount則是對象創建時將modCount的值賦給它,也就是說expectedModCount存儲的是迭代器創建時元素的個數。
那么checkForComodification()方法其實在比較迭代期間,ArrayList元素的個數 是否發生了改變,如果改變了,就拋出異常。
注意,expectedModCount除了在聲明時賦值外,也在remove()方法中更新了一次。