Java 编程错误:java.util.ConcurrentModificationException [英] Java Programming Error: java.util.ConcurrentModificationException

查看:34
本文介绍了Java 编程错误: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);
    }
}

参见 ConcurrentModificationExceptionmodCountAbstractList.

这篇关于Java 编程错误:java.util.ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆