1

我在以下代码中得到 ConcurrentModificationException

当我运行代码时它运行良好但突然抛出异常,我猜是由于列表的修改,但我不知道如何修复它

if (myRulesIncr!=null)
{
    Iterator itReceivedRules = myRulesIncr.iterator();
    while (itReceivedRules.hasNext())
    {
      RuleModel currentReceived = (RuleModel) itReceivedRules.next();
      if (receivedRulesExisting!=null)
      {
        Iterator itReceivedRulesExisting = receivedRulesExisting.iterator();
        while (itReceivedRulesExisting.hasNext())
        {
            RuleModel currentExisting = (RuleModel) itReceivedRulesExisting.next();

            if(currentExisting.getRuleId().equals(currentReceived.getRuleId()))
            {
                //TODO:replace the rule else add it.
                if(currentReceived.getStatus()!="D")
                { 
                    //replace the existing rule with the new one
                    receivedRulesExisting.remove(currentExisting);
                    receivedRulesExisting.add(currentReceived);
                } 
                else
                {
                    receivedRulesExisting.remove(currentExisting); 
                }
            }
            else
            {
                //Add the new rule to the existing rules
                receivedRulesExisting.add(currentReceived);
            }
        }
      }
    }
}

请帮我解决这个问题。

4

2 回答 2

4

ConcurrentModificationException当被迭代的集合被外部修改时抛出,即不是通过迭代器。所以你需要使用Iterator.remove()来避免这个异常。此外,不要在迭代时直接添加到集合中,而是将要添加的项目存储在单独的集合中,然后再添加它们:

  List<RuleModel> toBeAdded = new ArrayList<RuleModel>();

  if(currentReceived.getStatus()!="D")
  { 
      //replace the existing rule with the new one
      itReceivedRulesExisting.remove();
      toBeAdded.add(currentReceived);
  } 
  else
  {
      itReceivedRulesExisting.remove(); 
  }

  ...
  // after the loop terminated:
  receivedRulesExisting.addAll(toBeAdded);

另请注意,我使用了通用集合 - 建议这样做,以确保类型安全并摆脱如下向下转换:

Collection<RuleModel> myRulesIncr = ...
...
Iterator<RuleModel> itReceivedRules = myRulesIncr.iterator();
...
RuleModel currentReceived = itReceivedRules.next();
于 2012-04-02T13:50:40.327 回答
0

这是在多线程环境中吗?如果是,请使用线程安全集合。CopyOnWriteArrayList或者Collections.synchronizedList

于 2012-04-02T13:55:32.447 回答