java迭代器 异常_java迭代器失效 | 学步园
今天在測試代碼的時候出現一個異常ConcurrentModificationException,該異常網上很多解決方案以及解釋,但我還是再記錄一遍吧。
代碼抽象出來是這樣的:
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List list=new ArrayList();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
for (Integer i : list) {//這是迭代
if(i==3){
list.remove(new Integer(i));//引起異常的操作
}
}
}
}
該代碼在運行期間就出現java.util.ConcurrentModificationException異常。
這個循環其實是對list進行迭代。
1.在迭代的時候怎么判斷是否還有下一個(hasNext()方法怎么實現):
public boolean hasNext() {
return cursor != size();
}
cursor:Index of element to be returned by subsequent call to next
size():是該list的size
所以只要兩者不相等,就認為還有元素。
2.迭代的時候怎么取下一個(next()方法怎么實現):
public E next() {
checkForComodification();
try {
E next = get(cursor);
lastRet = cursor++;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
modelCount: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.
expectedModCount:期望的modelCount
這2個變量是有迭代器自己來維護的。
上面這段程序出現異常是因為我們使用Collection里面的remove方法進行刪除,ArrayList的remove方法實現:
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; // Let gc do its work
}
modCount+1,導致modCount和expectedModCount不相等。
3.解決方法就是用迭代器自己的remove方法:
public void remove() {
if (lastRet == -1)
throw new IllegalStateException();
checkForComodification();
try {
AbstractList.this.remove(lastRet); //將modCount+1,實現如下
if (lastRet < cursor)
cursor--;
lastRet = -1;
expectedModCount = modCount; //維護
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
public E remove(int index) {
RangeCheck(index);
modCount++; //***
E oldValue = (E) elementData[index];
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
return oldValue;
}
總結
以上是生活随笔為你收集整理的java迭代器 异常_java迭代器失效 | 学步园的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《绍古辞》第十二句是什么
- 下一篇: 《楚乔传》楚乔恢复记忆 木珠被谁偷走了