For 循环中的 java.util.ConcurrentModificationException

Esm*_*ash 3 java for-loop concurrentmodification

我正在尝试编写一个IM软件,我想让用户离开对话并告诉他的伙伴他已经离开...我更喜欢使用for循环而不是迭代器,寻找所有用户并获取要求离开的用户并像这样删除他:

   for(Clientuser Cu: EIQserver.OnlineusersList)
          if(Cu.ID.equals(thsisUser.ID)) // find the user who ask to leave 
          {
          Omsg.setBody("@@!&$$$$@@@####$$$$"); //code means : clien! ur parter leaves...
                 sendMessage(Omsg); // sed message to thje partner with that code
                 EIQserver.OnlineusersList.remove(Cu);// remove the partner
                EIQserver.COUNTER--;// decrease counter.

          }
Run Code Online (Sandbox Code Playgroud)

我得到异常:java.util.ConcurrentModificationException

我正在使用迭代器,为了摆脱这个异常,我转换为 for,但同样的异常仍然出现!我怎样才能摆脱这个异常?

Kon*_*kov 7

使用迭代器而不是循环。例如:

Iterator<Clientuser> iterator = EIQserver.OnlineusersList.iterator();
while (iterator.hasNext()) {
    Clientuser next = iterator.next();
    if(next.ID.equals(thsisUser.ID)) {
        Omsg.setBody("@@!&$$$$@@@####$$$$"); 
        sendMessage(Omsg); 
        iterator.remove();// remove the partner
    }
}
Run Code Online (Sandbox Code Playgroud)