我正在迭代一个 CustomObject 列表,并且在执行此迭代时,我通过向此自定义对象的标签列表添加一个标签来改变此对象。我没有在 customObjects (List) 中添加或删除任何 CustomObject。我仍然收到 java.util.ConcurrentModifcationException。
public class CustomObject {
private List<Tag> tags;
// Getter for Tag
// Setter for tag
}
public class DummyClass {
List<CustomObject> addMissingTag(List<CustomObject> customObjects) {
for (CustomObject object:customObjects) { // line 5
// following method adds a tag to tags list of CustomObject
mutateObjectByAddingField(object); // line 7
// Some Code
}
return customObjects;
}
void mutateObjectByAddingField(CustomObject customObject) {//line 13
Boolean found = false;
for (Tag tag:customObject.getTags()) { // line 15
if ("DummyKey".equalsIgnoreCase(tag.getKey())) {
found = true;
break;
}
}
if (!found) {
Tag tag = new Tag("DummyKey", "false");
List<Tag> tags = customObject.getTags();
tags.add(tag);
customObject.setTags(tags);
}
}
}
这是堆栈跟踪:
java.util.ConcurrentModificationException: null
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901) ~[?:1.8.0_131]
at java.util.ArrayList$Itr.next(ArrayList.java:851) ~[?:1.8.0_131]
at DummyClass.mutateObjectByAddingField(DummyClass.java:15)
at DummyClass.addMissingTag(DummyClass.java:7)
这是否意味着即使我们只是尝试修改对象而不是从列表/集合中删除或添加,我们也可以获得 ConcurrentModifcationException?