Is this a valid way to find and remove item from a LinkedList in Java using a for each loop, is it possible that inconsistency may arise:
for(ObjectType ob : obList) {
if(ob.getId() == id) {
obList.remove(ob);
break;
}
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Others have mentioned the valid point that normally this is not how you
removean object from a collection. HOWEVER, in this case it’s fine since youbreakout of the loop once youremove.If you want to keep iterating after a
remove, though, you need to use an iterator. Otherwise you’ll get aConcurrentModificationException, or in the more general case, undefined behavior.So yes, if you
breakout of theforeachafter youremove, 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
ConcurrentModificationExceptionis checked and thrown by the iterator. Here, after theremove(which qualifies as concurrent modification), youbreakout 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 aremove, it will fail.I would treat this idiom similar to
goto(or rather, labeledbreak/continue): it may seem wrong at first, but when used wisely, it makes for a cleaner code.