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
    评论
迭代器(Iterator)是 Java 集合框架中的一个接口,用于遍历集合中的元素。迭代器提供了统一的访问集合元素的方式,无论是 List、Set 还是 Map 都可以使用迭代器进行遍历。 以下是使用迭代器的基本步骤: 1. 创建迭代器对象:通过调用集合类的 `iterator()` 方法获取迭代器对象。例如,对于 ArrayList,可以使用 `iterator()` 方法获取一个对应的迭代器对象。 ``` ArrayList<String> list = new ArrayList<>(); // 添加元素到列表... Iterator<String> iterator = list.iterator(); ``` 2. 遍历元素:使用迭代器对象的 `hasNext()` 方法来判断是否还有下一个元素,使用 `next()` 方法获取下一个元素的值。 ``` while (iterator.hasNext()) { String element = iterator.next(); // 对元素进行操作... } ``` 3. 删除元素(可选):使用迭代器对象的 `remove()` 方法删除当前元素。注意,只能在调用 `next()` 方法之后调用 `remove()` 方法,否则会抛出 `IllegalStateException` 异常。 ``` iterator.remove(); ``` 迭代器的好处是可以在遍历集合时进行删除操作,而不会引发并发修改异常。此外,迭代器还提供了其他方法,如 `forEachRemaining()` 可以对剩余元素执行某个操作。 需要注意的是,迭代器是一次性的,即遍历完集合之后,需要重新获取迭代器对象才能再次遍历。同时,当集合发生结构性变化(如添加或删除元素)时,迭代器失效,需要重新获取。 希望以上解答对您有所帮助!如有更多问题,请随时提问。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值