从列表中删除项目时的Java并发修改异常

Zac*_*ach 1 java android

可能重复:
ArrayList上的java.util.ConcurrentModificationException

我试图从线程内的列表中删除项目.我得到了 ConcurrentModificationException.我从这个链接中读到它与从列表中删除项目有关.我将下面的示例代码.在我的情况下,如何在没有此例外情况下正确执行此操作.

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";
}
Run Code Online (Sandbox Code Playgroud)

Evg*_*eev 5

使用迭代器:

Iterator<Game> i = appDeleg.getGlobalGames().getGames().iterator();

Game game;
while(i.hasNext()) {
    game = i.next();
    if(game.getOwner().getId().equals(params[0]))
          i.remove();
    }
}
Run Code Online (Sandbox Code Playgroud)