Java – why doesn’t this code cause concurrentmodificationexception?

I'm reading about concurrentmodificationexception and how to avoid it Found an article The code for the first list in this article is similar to the following, which obviously leads to exceptions:

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 continue to explain how to solve the problem with various suggestions

When I tried to reproduce it, I got no exception! Why didn't I get an exception?

Solution

According to the Java API docs iterator Hasnext will not raise concurrentmodificationexception

After checking January and February, delete an element from the list Call it Hasnext() does not raise concurrentmodificationexception, but returns false Therefore, your code exits completely The last string is never checked If you add "April" to the list, you get "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

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>