ConcurrentModificationExcrption当我清除主列表后的子列表时,为什么以下代码抛出,但如果我清除子列表然后清除主列表则不会?
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??
Run Code Online (Sandbox Code Playgroud)
SubList不是一个独立的实体,但它只是给出原始列表的视图,并且内部引用相同的列表。因此,它的设计似乎是这样的:如果底层列表在结构上进行了修改(添加/删除元素),它就无法履行其合同。
从 SubList 的源代码中可以看出,该方法checkForComodification检查底层列表是否已被修改,因此如果modCount(列表结构上被修改的次数)值SubList与parent不同ArrayList,则抛出异常ConcurrentModificationException
因此,清除创建ArrayList的父级SubList可能会导致某些操作SubList导致 ConcurrentModificationException