Why isn#39;t this code causing a ConcurrentModificationException?(为什么这段代码不会导致 ConcurrentModificationException?)
问题描述
我正在阅读有关 ConcurrentModificationException 以及如何避免它的信息.找到一篇文章.该文章中的第一个清单具有类似于以下的代码,这显然会导致异常:
I was reading about ConcurrentModificationException and how to avoid it. Found an article. The first listing in that article had code similar to the following, which would apparently cause the exception:
List<String> myList = new ArrayList<String>();
myList.add("January");
myList.add("February");
myList.add("March");
Iterator<String> it = myList.iterator();
while(it.hasNext())
{
String item = it.next();
if("February".equals(item))
{
myList.remove(item);
}
}
for (String item : myList)
{
System.out.println(item);
}
接着用各种建议解释了如何解决问题.
Then it went on to explain how to solve the problem with various suggestions.
当我试图重现它时,我没有得到异常!为什么我没有收到异常?
When I tried to reproduce it, I didn't get the exception! Why am I not getting the exception?
推荐答案
根据Java API docs Iterator.hasNext 不会抛出 ConcurrentModificationException
.
According to the Java API docs Iterator.hasNext does not throw a ConcurrentModificationException
.
检查 "January"
和 "February"
后,您从列表中删除一个元素.调用 it.hasNext()
不会抛出 ConcurrentModificationException
而是返回 false.因此,您的代码干净地退出.然而,最后一个字符串永远不会被检查.如果您将 "April"
添加到列表中,则会按预期获得异常.
After checking "January"
and "February"
you remove one element from the list. Calling it.hasNext()
does not throw a ConcurrentModificationException
but returns false. Thus your code exits cleanly. The last String however is never checked. If you add "April"
to the list you get the Exception as expected.
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String args[]) {
List<String> myList = new ArrayList<String>();
myList.add("January");
myList.add("February");
myList.add("March");
myList.add("April");
Iterator<String> it = myList.iterator();
while(it.hasNext())
{
String item = it.next();
System.out.println("Checking: " + item);
if("February".equals(item))
{
myList.remove(item);
}
}
for (String item : myList)
{
System.out.println(item);
}
}
}
http://ideone.com/VKhHWN
这篇关于为什么这段代码不会导致 ConcurrentModificationException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么这段代码不会导致 ConcurrentModificationExcep


基础教程推荐
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01