java - How Iterator's remove method actually remove an object -
java - How Iterator's remove method actually remove an object -
we know safest "and safe" way of removing object collection while iterating it, first retrieving iterator
, perform loop , remove when needed;
iterator iter=collection.iterator(); while(iter.hasnext()){ object o=iter.next() if(o.equals(what i'm looking for)){ iter.remove(); } }
what understand, , unfortunately haven't found deep technical explanation about, how removal performed, if:
for(object o:mycollection().getobjects()){ if(o.equals(what i'm looking for)){ mycollection.remove(o); } }
will throw concurrentmodificationexception
, "in technical terms" iterator.remove()
do? removes object, breaks loop , restart loop?
i see in official documentation:
"removes current element. throws illegalstateexception
if effort made phone call remove()
not preceded phone call next( )."
the part "removes current element", makes me think of exact same situation happening in "regular" loop => (perform equality test , remove if needed), why iterator loop concurrentmodification-safe?
how iterator removes elements depends on implementation, may different different collections. doesn't break loop you're in. i've looked how arraylist iterator implemented , here's code:
public void remove() { if (lastret < 0) throw new illegalstateexception(); checkforcomodification(); seek { arraylist.this.remove(lastret); cursor = lastret; lastret = -1; expectedmodcount = modcount; } grab (indexoutofboundsexception ex) { throw new concurrentmodificationexception(); } }
so checks concurrent modifications, removes element using public arraylist remove method, , increments counter of list modifications concurrentmodificationexception won't thrown @ next iteration.
java loops collections iterator
Comments
Post a Comment