【发布时间】: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 循环或复制构造函数。请问你能展示一下迭代的代码吗?