Java programming error: java.util.ConcurrentModificationException

I am writing a program as part of a 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 is the method itself, inside the Warehouse class:

 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 related to the if else statement. If I do not enable if else, the program will start, although it will not work properly, because the loop will not go through an empty ArrayList.

I tried to add the product so that it was not empty in other parts of the code, but it still gives me the same error. Any ideas?

+4
source share
2 answers

You must not modify mCatalog during retry. You add 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 .

+4
source

You cannot iterate on the same list you are going to add to. Keep a separate list of the things you are going to add, then add them all at the end.

+6
source

Source: https://habr.com/ru/post/1386940/


All Articles