变异对象时的java.util.ConcurrentModificationException

变异对象时的java.util.ConcurrentModificationException,java,iterator,concurrentmodification,fail-fast,java-failsafe,Java,Iterator,Concurrentmodification,Fail Fast,Java Failsafe,我在一个CustomObject列表上进行迭代,在迭代过程中,我通过向这个自定义对象的标记列表添加一个标记来改变这个对象。我不会在customObjects(列表)中添加或删除任何CustomObject。我仍然得到java.util.ConcurrentModificationException public class CustomObject { private List<Tag> tags; // Getter for Tag // Setter fo

我在一个CustomObject列表上进行迭代,在迭代过程中,我通过向这个自定义对象的标记列表添加一个标记来改变这个对象。我不会在customObjects(列表)中添加或删除任何CustomObject。我仍然得到java.util.ConcurrentModificationException

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);
    }
  }

}

这是否意味着即使我们只是尝试修改对象,而不是从列表/集合中删除或添加对象,也可以获得ConcurrentModificationException?

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

使用
迭代器
时,您不能对正在迭代的列表进行修改,如上所述,您将获得
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      
 }
for(int i=0;i
您能通过添加字段方法代码向我们展示MutateObject吗?@Ismail:我用方法的实现更新了这个问题。您展示的代码中似乎没有一个能够导致ConcurrentModificationException。请创建一个实例来演示您遇到的问题。您的代码没有显示有关问题原因的任何线索。这段代码运行良好。你能给我们看一下完整的stacktrace吗?Thansk@Ismail,我用stacktrace更新了这个问题。这个链接很好地解释了传统for循环和基于迭代器的for循环之间的区别:使用传统for循环的一个主要优点是它允许你修改列表,这正是我所需要的。很好,如果以上几行回答了您的问题,请将其标记为正确的一行,以便让其他人知道。如果答案需要更详细的信息,请编辑它。谢谢@Ismail,我会在测试过程中验证后再做。但这似乎是正确的解决方案。
 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      
 }