【问题标题】:Why is `ArrayList.add` causing a ConcurrentModificationException? [duplicate]为什么 `ArrayList.add` 会导致 ConcurrentModificationException? [复制]
【发布时间】:2021-10-20 13:20:51
【问题描述】:

试图结束一个项目。除了不能将动物实例化到指定的数组之外,一切都在其中工作。这一行是我的导师给我的代码,所以我更加茫然。这是我用来声明数组列表的:

private static ArrayList<Dog> dogList = new ArrayList<Dog>();

然后我收集我需要的信息并使用下面的代码尝试将其添加到数组列表中。 nthDog 是之前声明的变量,参数正确。

 Dog nthDog = new Dog(name, breed, gender, age, weight, acquisitionDate,
            acquisitionCountry, trainingStatus, reserved, inServiceCountry);
 dogList.add(nthDog);

此代码是我的导师发送给我的,但是,在使用时它会显示错误 ConcurrentModificationException 和 checkForComodification。无法弄清楚可能出了什么问题。

【问题讨论】:

  • 我们需要更多代码来查看导致此类错误的原因,最好是查看所有使用了dogList 的地方,或者更多关于add 调用的上下文。
  • 在此之前随机猜测:您是否在迭代 dogList 时添加它?
  • ConcurrentModificationException 要求有一个 Iterator,无论是明确的还是隐含的,例如使用 for-each 循环或复制构造函数。请问你能展示一下迭代的代码吗?

标签: java arrays arraylist


【解决方案1】:

您可能在使用快速失败迭代器迭代集合时直接修改集合,迭代器将抛出此异常。

有关 ConcurrentModificationException 的更多详细信息,请参阅https://docs.oracle.com/javase/7/docs/api/java/util/ConcurrentModificationException.html

【讨论】:

    猜你喜欢
    • 2013-01-18
    • 2015-09-15
    • 1970-01-01
    • 2011-06-29
    • 2020-01-29
    • 2016-07-29
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多