一:概念
迭代器:對Collection進行迭代
二:源碼中的參數介紹
Collection接口的定義:
public interface Collection<E> extends Iterable<E>
Iterable<E>接口的定義:
public interface Iterable<T> {
Iterator<T> iterator();
}
Iterator的定義:
public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}
Java中的Iterator功能比較簡單,並且只能單向移動:
(1) 使用方法iterator()要求容器返回一個Iterator。第一次調用Iterator的next()方法時,它返回序列的第一個元素。
注意:iterator()方法是java.lang.Iterable接口,被Collection繼承。
(2) 使用next()獲得序列中的下一個元素,(若沒有下一個元素了,調用它會拋出一個NoSuchElementException異常)。
(3) 使用hasNext()判斷是否還有下一個元素(即是否遍歷完對象了)。
(4) 使用remove()將移除最近一次調用next方法返回的元素,(若沒有調用next方法而直接調用remove方法會報錯)。
三: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異常)。
(1)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()就沒有問題,在源碼中發現,在Iterator的remove()中同步了expectedModCount的值,所以當下次再調用next()的時候,檢查不會拋出異常。
使用該機制的主要目的是爲了實現ArrayList中的快速失敗機制(fail-fast),在Java集合中較大一部分集合是存在快速失敗機制的。
快速失敗機制產生的條件:
當多個線程對Collection進行操作時,若其中某一個線程通過Iterator遍歷集合時,該集合的內容被其他線程所改變,則會拋出ConcurrentModificationException異常。
所以要保證在使用Iterator遍歷集合的時候不出錯誤,就應該保證在遍歷集合的過程中不會對集合產生結構上的修改。
(2) 使用Foreach時對集合的結構進行修改會出現異常:
實現了Iterable接口的類就可以通過Foreach遍歷,因爲foreach要依賴於Iterable接口返回的Iterator對象,從本質上來講,Foreach其實就是在使用迭代器,在使用foreach遍歷時對集合的結構進行修改,和在使用Iterator遍歷時對集合結構進行修改本質上是一樣的,同樣的也會拋出異常,執行快速失敗機制。
(3) for循環與迭代器的對比:
* 效率上各有各的優勢:
1)ArrayList對隨機訪問比較快,而for循環中使用的get()方法,採用的即是隨機訪問的方法,因此在ArrayList裏for循環快。
2) LinkedList則是順序訪問比較快,Iterator中的next()方法採用的是順序訪問方法,因此在LinkedList裏使用Iterator較快。
3) 主要還是要依據集合的數據結構不同的判斷。