问题描述
我在写一些Java code和很惊讶地看到ConcurrentModificationException的。我写了一小块code的再现相同的。请通过以下code。
I was writing some code in Java and was surprised to see ConcurrentModificationException. I have written a small piece of code to reproduce the same. Kindly go through the below code.
ArrayList<Integer> masterList = new ArrayList<Integer>();
List<Integer> subList;
// Add some values to the masterList
for (int i = 0; i < 10; i++) {
masterList.add(i * i);
}
// Extract a subList from the masterList
subList = masterList.subList(5, masterList.size() - 1);
// The below throws ConcurrentModificationException
masterList.clear();
subList.clear(); // Exception thrown in this line
// The below doesn't throw any exception
subList.clear();
masterList.clear(); // No exception thrown. Confused??
我已经通过Java文档的ConcurrentModificationException的走了,也看到了对计算器和其他网站的众多code样品。但他们都不是类似我的。
I have gone through the Java Docs for ConcurrentModificationException and have also seen numerous code samples on StackOverflow and other websites. But none of them are similar to mine.
有人可以请解释一下,如果我清除子列表第一,那么为什么没有抛出异常的masterList?
Can someone please explain why exception is not thrown if I clear the "subList" first and then the "masterList"?
推荐答案
SUBLIST
不是一个独立的实体,但它只是给原始列表的视图,内部指的是同一个列表。因此,它的设计似乎是这样的,如果基础列表结构改性(添加/删除元素)时,它是不能够履行合同。
SubList
is not an independent entity, but it is just giving a view of the original list, and internally refers to same list. Hence, its design seem to be such that if underlying list is modified structurally (addition/removal of elements), it is not able to fulfill its contract.
如可以看到的<一个href=\"http://grep$c$c.com/file/repository.grep$c$c.com/java/root/jdk/openjdk/6-b14/java/util/ArrayList.java#ArrayList.SubList.checkForComodification%28%29\"相对=nofollow>在这里SUBLIST 源$ C $ C,该方法 checkForComodification
检查基础列表是否已被修改,因此如果 modCount的
(次数的名单已经结构修改)的值 SUBLIST
不一样的父的ArrayList
,然后,它抛出 ConcurrentModificationException的
As can be seen here in the source code of SubList, the method checkForComodification
checks whether the underlying list has been modified, and thus if the modCount
(number of times the list has been structurally modified) value of SubList
is not same as parent ArrayList
, then, it throws ConcurrentModificationException
所以,清除父的ArrayList
从 SUBLIST
创建可导致<$ C $的某些操作C>子列表导致ConcurrentModificationException的
So, clearing parent ArrayList
from which SubList
was created can result in the certain operations of SubList
to result in ConcurrentModificationException
这篇关于Java的ConcurrentModificationException的结算时,列表和ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!