For 循环中的 java.util.ConcurrentModificationException

标签 java for-loop concurrentmodification

我正在尝试编写一个 IM 软件, 我想让用户离开对话并告诉他的搭档他已经离开了...... 我更喜欢使用 for 循环而不是 Iterator,寻找所有用户并找到要求离开的用户并删除他......就像那样:

   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.

          }

我得到异常:java.util.ConcurrentModificationException

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

最佳答案

使用Iterator而不是循环。例如:

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
    }
}

关于For 循环中的 java.util.ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19702461/

相关文章:

java - 集合 - Iterator.remove() 与 Collection.remove()

java - 编译器警告对 Web 应用程序性能有影响吗

java - 如何更改子类中字段的通用类型?

Javascript - 使用 for 循环添加元素 id

python - 将python for循环转换为while循环

C中链表的并发修改

java 获取价格和符号

Java ip2long 等价物

python - 无法理解函数行为 - isprime()

Java在不同地方同时修改列表