我正在尝试编写一个 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/