您的位置:首页 > 编程语言 > Java开发

java迭代器失效

2013-02-25 13:37 309 查看
今天在测试代码的时候出现一个异常ConcurrentModificationException,该异常网上很多解决方案以及解释,但我还是再记录一遍吧。

代码抽象出来是这样的:

import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Integer> list=new ArrayList<Integer>();
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 <i>structurally modified</i>.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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: