Enhanced for (or 'for each') loop iterating to element it just removed - throws error
could not find anything on this, wondering if anyone knew about this or a possible workaround. I am using JDOM and working with an xml schema.
I have created a List of which are just xml tags. The algorithm's aim is to iterate through the List of elements and remove the element if a condition is met (in this case if it starts with a certain string). See below:
for (Element appinfo : appinfos) {
if (appinfo.getText().startsWith(
PARAMETER_DESCRIPTION_APPINFO)) {
removeAppInfoElement(appinfo, name, appinfo.getText());
}
}
However, the loop appears to be attempting to iterate to the element it just removed. Does an开发者_运维百科yone see anything wrong with this? Do I need to abandon the enhanced for loop or dig deeper for cause of problem?
I suppose you're talking about ConcurrentModificationException. Try to use iterator instead.
Yes that wont work.
Add all the items you want to remove to a new collection and then do a removeAll
with those elements on the original collection.
You cannot remove elements from a Collection directly as you iterate over it - this causes issues because the Iterator has no idea that the element has been removed.
Instead of the enhanced for-loop, use the Iterator
directly and call the remove()
function, for example:
for (Iterator it = appinfos.iterator(); it.hasNext();) {
Element appinfo : it.next();
if (someCondition) {
it.remove();
}
}
willcodejavaforfood's answer is one way of doing this.
An alternative, which may be better or worse depending on style and what else you want to do in the loop, is to get the Iterator
explicitly and use its remove
method:
final Iterator<Element> iter = appinfos.iterator();
while (iter.hasNext()) {
if (iter.next().getText().startsWith(
PARAMETER_DESCRIPTION_APPINFO)) {
iter.remove();
}
}
This of course only works if a simple removal from the collection is what you want to do. When invoking potentially complex methods that will directly remove from the underlying collection, the best approach is to take a copy of the collection initially, then iterate over this copy.
In all cases, modifying a collection while you are iterating over it will generally cause Bad Things to happen.
精彩评论