【问题标题】:Java concurrent modification exception when removing items from list [duplicate]从列表中删除项目时Java并发修改异常[重复]
【发布时间】:2012-11-23 11:38:54
【问题描述】:

可能重复:
java.util.ConcurrentModificationException on ArrayList

我正在尝试从线程内的列表中删除项目。我收到了ConcurrentModificationException。我从link 中读到它与从列表中删除项目有关。我将示例代码放在下面。在我的情况下,如果没有这个例外,我怎样才能正确地做到这一点。

try 
{
    for(Game game:appDeleg.getGlobalGames().getGames())
    {
        if(game.getOwner().getId().equals(params[0]))
        {
            synchronized (appDeleg.getGlobalGames().getGames())
            {
                appDeleg.getGlobalGames().getGames().remove(game);
            }
        }

    }
}

catch (Exception e) 
{
    e.printStackTrace();
    return "noconnection";
}

【问题讨论】:

    标签: java android


    【解决方案1】:

    使用迭代器:

    Iterator<Game> i = appDeleg.getGlobalGames().getGames().iterator();
    
    Game game;
    while(i.hasNext()) {
        game = i.next();
        if(game.getOwner().getId().equals(params[0]))
              i.remove();
        }
    }
    

    【讨论】:

    • 我认为你必须使用Iterator&lt;Game&gt; i=appDeleg.getGlobalGames().getGames().iterator(); 来获取迭代器
    • 对,急着要投票:)
    【解决方案2】:

    增强的 for 循环使用迭代器。如果在迭代时修改了集合,迭代器可能会抛出异常。

    在您的情况下,您是通过集合而不是通过迭代器删除项目。

    尝试使用标准的 for 循环,而不是使用隐含的迭代器。 假设您的集合是一个数组列表。

    ArrayList games = appDeleg.getGlobalGames().getGames();
    for(int i=0;i<games.size();i++){
          Game game = games.get(i);
          if(game.getOwner().getId().equals(params[0])){
           games.remove(i);
    
          }
    }
    

    【讨论】:

    • 它在我使用 ArrayList 时对我有用
    【解决方案3】:

    在新列表中收集要删除的项目,并在遍历原始列表后将其删除。

    【讨论】:

    • 或者从迭代器本身而不是集合中删除项目。
    【解决方案4】:

    同步关键字不会在这里保护您。
    您可以从单线程应用程序访问此异常事件(是的 - 您可能会声称异常名称具有误导性)。
    这应该使用迭代器来遍历列表,
    (这将允许您在达到要删除的值时调用 remove),
    或者通过将要删除的元素收集到单独的列表中,然后对其运行 removeAll 方法。

    【讨论】:

      【解决方案5】:

      迭代时不能删除列表项,它会抛出ConcurrentModificationException

      如果列表在迭代器创建后的任何时间发生结构性修改, 除了通过迭代器自己的 remove 或 add 方法之外的任何方式,迭代器 将抛出 ConcurrentModificationException。因此,面对并发 修改,迭代器快速而干净地失败,而不是冒险任意, 未来不确定时间的非确定性行为。

      文档 -> link

      您应该 Iterator 从列表中删除项目。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-21
        • 2014-09-02
        • 2012-10-29
        • 1970-01-01
        • 1970-01-01
        • 2014-03-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多