java - 清除子列表时出现 ConcurrentModificationException

标签 java list

<分区>

为什么当我在主列表之后清除子列表时,下面的代码会抛出 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??

最佳答案

SubList 不是一个独立的实体,但它只是给出原始列表的一个 View ,并且在内部引用同一个列表。因此,它的设计似乎是这样的,如果基础列表在结构上被修改(添加/删除元素),它就无法履行其契约(Contract)。

可以看出here in the source code of SubList ,方法 checkForComodification 检查底层列表是否已被修改,因此 modCount (列表被结构修改的次数)值是否为 SubList 与父级 ArrayList 不同,则抛出 ConcurrentModificationException

因此,清除从中创建 SubList 的父级 ArrayList 可能会导致 SubList 的某些操作导致 ConcurrentModificationException

关于java - 清除子列表时出现 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17899738/

相关文章:

python - 正确格式的列表元素的长度

java - 如何使用数组为 Java 中的单个字符串分配多个值?

Java - 线程、Swing 和 ServerSocket

java - 一个类是自动生成的,它没有被编译,编译错误是 "code too large"

java - 部署在 Tomcat 上的 Spring Boot MVC 应用程序无法正常工作

python-3.x - 为什么Python在这段看似简单的代码中不拼接换行符呢?

r - 将数据框列表写入多个 excel 文件

r - 如何根据数据框名称中的单个字符在数据框中添加新列?

algorithm - 通过每次从 N 个列表中选择一个数字来从 N 个列表中找到第 k 个最大数字的高效算法

java - 为什么 threadpooltest 没有正确运行?