送交者: 松鼠 于 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.