java - subList() 之后出现 ConcurrentModificationException

标签 java unit-testing

我在单元测试中遇到了这个问题。

执行后:

List<Card> cleanCards = cards.subList(0, cards.size() - difference);

以下断言给了我一个 ConcurrentModificationException:

assertEquals(limit, cleanCards.size());

错误描述

java.util.ConcurrentModificationException 
at java.util.ArrayList$SubList.size(ArrayList.java:1057)

据我所知,“size()”方法不会对列表进行结构更改。我在这里遗漏了什么吗?

最佳答案

很可能原始列表在子列表创建和使用之间被修改。 subList 不会创建一个独立的新列表,而是创建原始列表的一部分的 View ,如specs

The semantics of the list returned by this method become undefined if the backing list (i.e., this list) is structurally modified in any way other than via the returned list. (Structural modifications are those that change the size of this list, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.)

在您的情况下,“未定义”行为似乎会导致抛出异常,也称为快速失败行为。我认为一个简单的解决方案是将上面的第一行更改为

List<Card> cleanCards = new ArrayList<>(cards.subList(0, cards.size() - difference));

它将子列表复制到一个独立于原始列表的全新列表。

关于java - subList() 之后出现 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47890998/

相关文章:

java - 在后台缓存 CSS 和 Javascript 或从应用程序加载它们

java - 强制 Java 运行时在 NSF 中使用 Jar 而不是在 XPages 应用程序的同名服务器上使用 Jar

JAVA如何找到符号链接(symbolic link)指向的目标文件路径?

java - Redis 复制问题

python - 如何防止 Django 测试在文档字符串中运行示例?

c++ - 在 C++ 中模拟非类方法

ruby-on-rails - 使用 FactoryGirl 加速模型规范中的关联 - create vs build vs build_stubbed

ruby - 什么是适合 Rails 3 的测试框架?

java - 使用 JMF 播放 MP4 视频

python - 我们如何确保 Mock.call_args_list 中的调用包含参数与调用 Mock 对象时处于相同状态的调用?