With an iterator you can remove an element from the underlying collection using the iterator.remove() method, like this
Iteratorit = somelist.iterator();
while (it.hasNext())
{
MyObject o = it.next();
// o.dosomething();
it.remove(); // removes the current object from the list
}
This is no longer visible if you change from iterator to for-each:
for (MyObject o : somelist)
{
// o.dosomething();
somelist.remove(o); // removes o from the list
}
Since the iterator is not exposed to your code, the pitfall is to remove the object directly from the collection...
This will cause a ConcurrentModificationException... not a nice thing to do. But actually its quite clear and obvious.
Afterwards...
No comments:
Post a Comment