java.util.ConcurrentModificationException 改变对象时

java.util.ConcurrentModificationException while mutating an object

我正在迭代 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 即使我们只是尝试修改对象而不是删除或添加 from/to list/collection?

首先,您在 for 循环中使用 List 类型来迭代元素,因此增强的 for 语句等同于使用迭代器的 for ,如前所述 here,因为 List 实现了 Iterator。此外,从堆栈跟踪中可以明显看出。

当使用Iterator时,您不能对正在迭代的列表进行修改,如GeeksForGeeks所述,您将得到ConcurrentModificationException

因此,要解决此问题,您可以使用如下整数显式实现 for 循环:

 for (int i=0;i < customObjects.length(); i++) {

      CustomObject object = customObjects.get(i);

      // following method adds a tag to tags list of CustomObject
      mutateObjectByAddingField(object);
      // Some Code      
 }