Java Programming Error: java.util.ConcurrentModificationException

假装没事ソ 提交于 2019-12-23 13:09:14

问题


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)

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

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?


回答1:


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

See ConcurrentModificationException and modCount in AbstractList.




回答2:


You can't be iterating through the same list you're going to add things to. Keep a separate list of the things you're going to add, then add them all at the end.



来源:https://stackoverflow.com/questions/8553713/java-programming-error-java-util-concurrentmodificationexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!