为什么这段代码不会导致ConcurrentModificationException? [英] Why isn't this code causing a ConcurrentModificationException?

查看:125
本文介绍了为什么这段代码不会导致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文档 Iterator.hasNext 不会抛出 ConcurrentModificationException

According to the Java API docs Iterator.hasNext does not throw a ConcurrentModificationException.

检查January和<$ c后$ c>二月从列表中删除一个元素。调用 it.hasNext()不会抛出 ConcurrentModificationException 但返回false。因此,您的代码会干净利落地退出。但是从不检查最后一个String。如果您将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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆