我已经阅读了一篇关于从此链接中删除集合中的元素的文章
根据我的理解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)
任何人都可以解释这段代码中幕后发生的事情吗?
如果我注释掉 dayList.remove("Tuesday"); 行,则会抛出异常......
\n\n其实这在这里不是问题。问题是仅中间值发生异常。
\n\n\xe2\x80\x98 对于每个 \xe2\x80\x99 循环的工作原理如下,
\n\n1.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}\nRun 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\ncursor = 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.\nRun Code Online (Sandbox Code Playgroud)\n\n在您的情况下,当您删除 \xe2\x80\x98d\xe2\x80\x99 时,大小会减少到 4。
\n\ncursor = 4 size = 4 --> hasNext() does not succeed and next() is skipped.\nRun Code Online (Sandbox Code Playgroud)\n\n在其他情况下,将抛出 ConcurrentModificationException \nas modCount != ExpectedModCount。
\n\n在这种情况下,不会进行此检查。
\n\n如果您尝试在迭代时打印元素,则只会打印四个条目。最后一个元素被跳过。
\n\n你的问题和这个问题很相似。
\n| 归档时间: |
|
| 查看次数: |
935 次 |
| 最近记录: |