用iterator遍历集合时要注意的地方:不可以对iterator相关的地方做添加或删除操作。
下面用List为例来说明为什么会报 ConcurrentModificationException 这个异常,其它集合类似可以自己思考。
public static void main(String[] args)
{
List<String> set = new ArrayList<String>();
set.add("a10001");
set.add("a10002");
set.add("a10003");
set.add("a10004");
set.add("a10005");
set.add("a10006");
set.add("a10007");
List<String> del = new ArrayList<String>();
del.add("a10003");
del.add("a10004");
del.add("a10005");
for(String str : set)
{
if(del.contains(str))
{
set.remove(str);
}
}
}
运行这段代码的结果
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at com.debug.Debug.main(Debug.java:28)
大家都知道for(String str : set) 这句话实际上是用到了集合的iterator() 方法
在iterator的时候是产生了一个List的内部类Itr
JDK源码
public Iterator<E> iterator() {
return new Itr();
}
在new Itr()时有一个关键性的操作
/**
* The modCount value that the iterator believes that the backing
* List should have. If this expectation is violated, the iterator
* has detected concurrent modification.
*/
int expectedModCount = modCount;
再回头看一下List 的 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
}
再看一下 iterator.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();
}
相信看到这儿大家已经应该明白了为什么会出现在这个异常了。
总结:
iterator 时 将expectedModCount = modCount 在remove()时 modCount++ 在next()时
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
一旦删除或添加元素后 modCount ,expectedModCount 这两个值就会不一致 当next时就会报ConcurrentModificationException
了解了原由,解决方案就很简单了 在遍历时用一个集合存放要删除的对象 在遍历完后 调用removeAll(Collection<?> c) 就OK了。
分享到:
相关推荐
java.util.ConcurrentModificationException 异常问题详解1
本文通过对数据压缩算法的简要介绍,然后以详细的示例演示了利用java.util.zip包实现数据的压缩与解压,并扩展到在网络传输方面如何应用java.util.zip包现数据压缩与解压
1. java.util.concurrent - Java 并发工具包 2. 阻塞队列 BlockingQueue 3. 数组阻塞队列 ArrayBlockingQueue 4. 延迟队列 DelayQueue 5. 链阻塞队列 LinkedBlockingQueue 6. 具有优先级的阻塞队列 ...
java.util.ConcurrentModificationException 解决方法 在使用iterator.hasNext()操作迭代器的时候,如果此时迭代的对象发生改变,比如插入了新数据,或者有数据被删除。 则使用会报以下异常: Java.util....
详细介绍了java.util.logging.Logger的用法和结构,对如果扩展Logger起到抛砖引玉的作用!尊重劳动成果,亲下载了要给个评价!
Tomcat内存溢出的解决方法(java.util.concurrent.ExecutionException:java.lang.OutOfMemoryError),内附解决方案!
Exception in thread “main“ java.util.InputMismatchException
主要介绍了出现java.util.ConcurrentModificationException 问题及解决办法的相关资料,需要的朋友可以参考下
java.util.Date与java.sql.Date互转及字符串转换为日期时间格式.docx
java.util.concurrent系列文章(1) java.util.concurrent系列文章(1) java.util.concurrent系列文章(1) java.util.concurrent系列文章(1)
java并发工具包 java.util.concurrent中文版-带书签版
这是我在编写struts2中遇到的问题,整理出来,包括截图,希望可以帮到大家
详细介绍java.util.Date和java.sql.Date相互转换的多种方法总结,希望对大家有帮助
java.util包
世界范围内的时区列表。由 java.util.TimeZone 类导出
java.util包源码,pdf版,方便打印
使用java.util.timer实现的简单定时任务,在实现简单一次性定时任务时,使用java.util.timer非常的简单易用,适合没有接触过quartz的新手急用。
java.util.pdf
java.util.concurrent总体概览图。 收取资源分3分。需要的同学可以下载一下。 java.util.concurrent主要包括5个部分executor,colletions,locks,atomic,tools。 该图详细的列举了并发包下面的结构,包含所有接口和...