Others have mentioned the valid point that normally this is not how you remove
an object from a collection. HOWEVER, in this case it's fine since you break
out of the loop once you remove
.
If you want to keep iterating after a remove
, though, you need to use an iterator. Otherwise you'll get a ConcurrentModificationException
, or in the more general case, undefined behavior.
So yes, if you break
out of the foreach
after you remove
, you'll be fine.
To those who's saying that this will fail because you can't modify a collection in a foreach
-- this is true only if you want to keep iterating. That's not the case here, so this shortcut is fine.
A ConcurrentModificationException
is checked and thrown by the iterator. Here, after the remove
(which qualifies as concurrent modification), you break
out of the loop. The iterator doesn't even get a chance to detect it.
It may be best if you add a comment on the break
, why it's absolutely necessary, etc, because if this code is later modified to continue iterating after a remove
, it will fail.
I would treat this idiom similar to goto
(or rather, labeled break
/continue
): it may seem wrong at first, but when used wisely, it makes for a cleaner code.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…