java迭代器失效

今天在测试代码的时候出现一个异常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;
}


  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值