foreach()
通過編譯+IDE工具反編譯+Debug發現foreach方法的底層實現是Iterator(迭代器)。
for(Iterator var2 = list.iterator(); var2.hasNext(); var3 = (String)var2.next()) {
;
}
原理:當foreach循環的時候通過調用List中的iterator()方法返回一個Iterator對象,此對象是new Itr() 這個內部類得到的,然後用該對象調用對應方法實現相應操作。源碼如下:
/**
* Returns an iterator over the elements in this list in proper sequence.
*
* <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
*
* @return an iterator over the elements in this list in proper sequence
*/
public Iterator<E> iterator() {
return new Itr();
}
1. 認識ArrayList類中的內部類:Itr
根據ArrayList中的對於Itr這個內部類的註釋得知,此內部類是AbstractList中的內部類Itr的優化版本,源碼如下:
/**
* 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;
Itr() {}
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();
}
}
2. 認識Itr中的相關方法
2.1 hasNext()
public boolean hasNext() {
return cursor != size;
}
分析:判斷遊標cursor與集合size是否相等。if 相等,then就沒有next 值了;if 不相等,說明還有next,就可以調用next方法取出next element。
變量:
cursor :源碼註釋爲index of next element to return, 意思是將要返回的下一個元素的索引)
size:遍歷的當前集合的大小
2.2 next()
@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];
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
分析:(1)檢查modCount與expectedModCount是否相等;(2)獲取下個元素的cursor;(3)將當前索引值賦給lastRet(4)返回當前元素
變量:
lastRet:源碼註釋爲index of last element returned, 意思是返回的最後一個元素的索引)
2.3 remove()
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();
}
}
分析:(1)檢查modCount與expectedModCount是否相等;(2)調用ArrayList的remove(int index)移除元素;(3)回退cursor和lastRet的值,並且同步modCount與expectedModCount的值
2.4 forEachRemaining(Consumer<? super E> consumer)省略
2.5 checkForComodification()
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
分析:檢查modCount與expectedModCount是否相等
3. foreach循環中執行List.remove(Object o)
當執行remove(Object o)方法時,modCount會自加1,並且此值沒有賦值給expectedModCount,cursor的值並沒有回退1,所以再次執行下一循環的時候,調用hasNext()方法返回值依然是true,此時就會執行next()方法,就會checkForComodification,然後modCount與expectedModCount並不相等,就會throw ConcurrentModificationException異常。
remove(Object o)
/**
* Removes the first occurrence of the specified element from this list,
* if it is present. If the list does not contain the element, it is
* unchanged. More formally, removes the element with the lowest index
* <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
* (if such an element exists). Returns <tt>true</tt> if this list
* contained the specified element (or equivalently, if this list
* changed as a result of the call).
*
* @param o element to be removed from this list, if present
* @return <tt>true</tt> if this list contained the specified element
*/
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
分析:此方法屬於ArrayList類中的實現方法,其底層調用的是fastRemove(int index)。
fastRemove(int index)
/*
* Private remove method that skips bounds checking and does not
* return the value removed.
*/
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
}
分析:此方法也是利用index移除元素。它與remove(int index)方法的比較 as follow:
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* @param index the index of the element to be removed
* @return the element that was removed from the list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
4. 原生迭代器執行Iterator.remove()方法
具體代碼:
Iterator<String> itr = list.iterator();
while (itr.hasNext()) {
String s = itr.next();
itr.remove();
}
此方法與foreach()明顯的不同在於調用remove方法。
- 執行iterator.remove()時,cursor&lastRet的值會被回退到上一次執行時的值、expectedModCount的值會被modCount重新賦值,所以當一次執行的時候判斷hasNext和獲取next 是正常的。
// Itr中的方法
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();
}
}
// ArrayList中的remove(int index)
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
- 執行list.remove(Object o)時,cursor、lastRet和expectedModCount均未被重新賦值,導致下一次執行循環的時候,拋出異常。另外,當移除最後一個元素也會拋出異常,因爲即使遍歷完畢foreach方法還會再進入一次執行hasNext() 方法,若返回true則調用next()方法,當checkForComodification()時會拋出異常
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
}