且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

并发修改执行

更新时间:2023-02-05 14:41:40

您正在迭代中进行添加.根据规范,不允许您修改要迭代的集合.

You're doing an add inside of your iteration. As per the spec, you're not allowed to modify the collection you're iterating over.

经典的解决方案是首先创建集合的副本,然后对其进行迭代.另一种解决方案是不使用迭代器(简短的foreach表示法是隐式使用它),而是使用索引手动进行迭代.

The classic solution is to make a copy of the collection first and iterate over that instead. Another solution is to not use the iterator (the short foreach notation is using it implicitly) but to manually iterate using an index.

for (int i=0; i<queues.size(); i++) {
    CallQueue callQueue = queues.get(i);

    ... code goes here

}

更好的解决方案是使用Set而不是列表(除非顺序对您很重要).那确实意味着您将必须正确实现equals和hashcode.

A better solution would be to use a Set instead of a list (unless the order is important for you). That does mean you would have to implement equals and hashcode properly.

顺便说一句:我相信您的代码有缺陷.您正在遍历列表,如果遇到的项目不匹配,则在末尾添加一个.这意味着,如果您要查找的项目是列表中的第x个项目,则您将添加x次新项目.我严重怀疑那是您所需要的.如果您进行一些重构,这将立即变得很清楚.