问题描述
为什么以下代码抛出 ConcurrentModificationExcrption
,当我清除主列表后的子列表时,但是如果我清除子列表然后清除主列表? / p>
Why does the following code throw ConcurrentModificationExcrption
, when I clear the sub List after the master List, but not if I clear the sub list and then the master List?
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??
推荐答案
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.
可以见过中,方法 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
会导致 SubList
的某些操作导致ConcurrentModificationException
So, clearing parent ArrayList
from which SubList
was created can result in the certain operations of SubList
to result in ConcurrentModificationException
这篇关于清除子列表时出现ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!