集合删除方法不会给出并发修改异常

cod*_*r25 7 java collections

我已经阅读了一篇关于从此链接中删除集合中的元素的文章

根据我的理解iterator remove方法防止并发修改异常然后删除Collection.But的方法当我尝试运行下面的codde我无法得到concurrentmoficationexception

     List dayList= new ArrayList();
     dayList.add("Sunday");
     dayList.add("Monday");
     dayList.add("Tuesday");
     dayList.add("Wednesday");
     dayList.remove("Tuesday");
     Iterator itr=dayList.iterator();
        while(itr.hasNext())
        {
           Object testList=itr.next();
           if(testList.equals("Monday"))
             {
            dayList.remove(testList);

             }
    }
    System.out.println(dayList);
}
Run Code Online (Sandbox Code Playgroud)
  • 根据javadoc,当我们尝试在iteartion期间进行任何修改时抛出ConcurrentModicationException.我正在使用集合remove方法,但仍然没有异常.但是如果我注释行dayList.remove("Tuesday"); ,抛出异常.

任何人都可以解释这段代码中幕后发生的事情吗?

Sam*_*azi 2

如果我注释掉 dayList.remove("Tuesday"); 行,则会抛出异常......

\n\n

其实这在这里不是问题。问题是仅中间值发生异常。

\n\n

\xe2\x80\x98 对于每个 \xe2\x80\x99 循环的工作原理如下,

\n\n
1.It gets the iterator.\n2.Checks for hasNext().\npublic boolean hasNext() \n{\n      return cursor != size(); // cursor is zero initially.\n}\n3.If true, gets the next element using next().\n\npublic E next() \n{\n        checkForComodification();\n        try {\n        E next = get(cursor);\n        lastRet = cursor++;\n        return next;\n        } catch (IndexOutOfBoundsException e) {\n        checkForComodification();\n        throw new NoSuchElementException();\n        }\n}\n\nfinal void checkForComodification() \n{\n    // Initially modCount = expectedModCount (our case 5)\n        if (modCount != expectedModCount)\n        throw new ConcurrentModificationException();\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

重复步骤 2 和 3,直到 hasNext() 返回 false。

\n\n

如果我们从列表中删除一个元素,它的\xe2\x80\x99s 大小会减小,modCount 会增加。

\n\n

如果我们在迭代时删除一个元素,则 modCount != ExpectedModCount 得到满足,并抛出 ConcurrentModificationException 。

\n\n

但是删除倒数第二个对象很奇怪。让我们看看它在您的案例中是如何工作的。

\n\n

最初,

\n\n
cursor = 0 size = 5 --> hasNext() succeeds and next() also succeeds without exception.\ncursor = 1 size = 5 --> hasNext() succeeds and next() also succeeds without exception.\ncursor = 2 size = 5 --> hasNext() succeeds and next() also succeeds without exception.\ncursor = 3 size = 5 --> hasNext() succeeds and next() also succeeds without exception.\n
Run Code Online (Sandbox Code Playgroud)\n\n

在您的情况下,当您删除 \xe2\x80\x98d\xe2\x80\x99 时,大小会减少到 4。

\n\n
cursor = 4 size = 4 --> hasNext() does not succeed and next() is skipped.\n
Run Code Online (Sandbox Code Playgroud)\n\n

在其他情况下,将抛出 ConcurrentModificationException \nas modCount != ExpectedModCount。

\n\n

在这种情况下,不会进行此检查。

\n\n

如果您尝试在迭代时打印元素,则只会打印四个条目。最后一个元素被跳过。

\n\n

你的问题和这个问题很相似。

\n