Java HashSet Problem.



所有跟贴·加跟贴·新语丝科技论坛

送交者: 松鼠 于 2005-11-10, 00:21:15:

I have a HashSet, and I want to traversal the whole set and find the bad elements and delete them. So my program is:

for (Iterator term = set.iterator(); term.hasNext(); ) {
Object o = (Object) term.next();
if (IsBad(o))
set.remove(o);
}

When I run it, I got an error
--------
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
at java.util.HashMap$KeyIterator.next(Unknown Source)
---------
in the line "term.next()", after one delete action is performed.

So I changed it as:
for (Iterator term = set.iterator(); term.hasNext(); ) {
Object o, oldo;
if (IsBad(o)){
oldo = o;
o = (Object) term.next();
set.remove(oldo);
}
else
o = (Object) term.next();
}

and get same error message
---------
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
at java.util.HashMap$KeyIterator.next(Unknown Source)
---------
and the timming is weired. In my sample, the first object is bad, others are good.
So the first round, the bad object is read, but do nothing.
Second round, because IsBad(o), so o=term.next(); and set.remove(oldo);
Third round, came to the else part, o = term.next();and got the error message.

So, how should I delete bad elements in a HashSet? I can change it to LinkedList if you think it can help.




所有跟贴:


加跟贴

笔名: 密码(可选项): 注册笔名请按这里

标题:

内容(可选项):

URL(可选项):
URL标题(可选项):
图像(可选项):


所有跟贴·加跟贴·新语丝科技论坛