Java编程错误:java.util.ConcurrentModificationException [英] Java Programming Error: java.util.ConcurrentModificationException
问题描述
我正在为Java初学者编写一个程序,作为本教程的一部分.我有以下方法,每当我运行它时,它都会给我以下异常:
I'm writing a program as part of tutorial for a beginner Java student. I have the following method and whenever I run it, it gives me the following exception:
java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at Warehouse.receive(Warehouse.java:48)
at MainClass.main(MainClass.java:13)
这是类Warehouse中的方法本身:
Here's the method itself, within the class Warehouse:
public void receive(MusicMedia product, int quantity) {
if ( myCatalog.size() != 0) { // Checks if the catalog is empty
// if the catalog is NOT empty, it will run through looking to find
// similar products and add the new product if there are none
for (MusicMedia m : myCatalog) {
if ( !m.getSKU().equals(product.getSKU()) ) {
myCatalog.add(product);
}
}
} else { // if the catalog is empty, just add the product
myCatalog.add(product);
}
}
问题似乎出在if else语句上.如果我不包含if else,则该程序将运行,尽管它将无法正常运行,因为该循环不会通过空的ArrayList进行迭代.
The problem seems to be with the if else statement. If I don't include the if else, then the program will run, although it won't work properly because the loop won't iterate through an empty ArrayList.
我试图添加一个产品只是为了防止它在代码的其他部分中为空,但是它仍然给我同样的错误.有什么想法吗?
I've tried adding a product just to keep it from being empty in other parts of the code, but it still gives me the same error. Any ideas?
推荐答案
在迭代mCatalog
时,不得修改它.您将在此循环中向其中添加元素:
You must not modify mCatalog
while you're iterating over it. You're adding an element to it in this loop:
for (MusicMedia m : myCatalog) {
if ( !m.getSKU().equals(product.getSKU()) ) {
myCatalog.add(product);
}
}