For循环中的java.util.ConcurrentModificationException [英] java.util.ConcurrentModificationException in For loop
问题描述
我正在尝试编写IM软件, 我想让用户离开对话,并告诉他的伴侣他已经离开了... 我更喜欢使用for循环而不是Iterator,寻找所有用户并让要离开并删除他的用户...像这样:
I am trying to program an IM software, I want to let user leave the conversation and tell his partner that he has left... I prefer to use for loop instead Iterator, seek all the users and get the user who ask to leave and remove him... like that:
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
I get Exception: java.util.ConcurrentModificationException
我正在使用迭代器,为了摆脱此异常,我将其转换为for,但是仍然出现相同的异常! 我如何摆脱这个例外?
I was using iterators, and to get rid of this exception, I convert to for, but the same exception still appears!! how may I get rid of this exception?
推荐答案
使用迭代器,而不是循环.例如:
Use Iterator instead of looping. For example:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!