Iterator stopped working!

The following code has worked excellent for over a year, and now it stops working:


Iterator itr =  mylist.iterator();
while(itr.hasNext()){                        
      myobject = (MyObject) itr.next();
        mylist.remove(myobject)
}

However if i use: itr.remove() instead it works. Any ideas?

Changing a collection while iterating through its elements is inherenty unsafe, and officially unsupported by all java.util collection objects. Iterator was created to address just this, as it provides a safe way to remove elements while iterator (unlike enumerator).

I’d guess they tightened up some code in the recent JRE upgrades, and your code as listed should (by spec) result in an exception. So bascially you were relying on undocumented behaviour.

Yeah… your code has been broken for well over a year now… it just didn’t fail yet :slight_smile:

In fact you were lucky to not have it through an exception - ConcurrentModificationException or something like that. It’s all documented if you look at the Iterator docs.

what about

mylist.clear();

?

;D

Why don’t you write your own iterator, it’s not difficult, that way you’ll know exactly what the calls are doing.