Java编程错误:java.util.ConcurrentModificationException

use*_*775 4 java exception arraylist concurrentmodification

我正在编写一个程序作为初学者Java学生的教程的一部分.我有以下方法,每当我运行它时,它给我以下异常:

  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)
Run Code Online (Sandbox Code Playgroud)

这是方法本身,在类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);
  }
}
Run Code Online (Sandbox Code Playgroud)

问题似乎与if else语句有关.如果我不包含if else,那么程序将运行,虽然它将无法正常工作,因为循环不会遍历空ArrayList.

我试过添加一个产品只是为了防止它在代码的其他部分变空,但它仍然给我同样的错误.有任何想法吗?

Kyl*_*lar 6

你不能迭代你要添加东西的同一个列表.保留您要添加的内容的单独列表,然后在最后添加所有内容.