我在单元测试中遇到了这个问题。
执行后:
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/