增强的 for(或“foreach”)循环迭代到刚刚删除的元素 - 抛出错误
找不到任何相关信息,想知道是否有人知道这一点或可能的解决方法。我正在使用 JDOM 并使用 xml 模式。
我创建了一个列表,其中只有 xml 标签。该算法的目标是迭代元素列表,并在满足条件时删除该元素(在本例中,如果它以某个字符串开头)。参见下文:
for (Element appinfo : appinfos) {
if (appinfo.getText().startsWith(
PARAMETER_DESCRIPTION_APPINFO)) {
removeAppInfoElement(appinfo, name, appinfo.getText());
}
}
但是,循环似乎正在尝试迭代到刚刚删除的元素。 有人看出这有什么问题吗?我是否需要放弃增强的 for 循环或深入挖掘问题原因?
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 anyone see anything wrong with this? Do I need to abandon the enhanced for loop or dig deeper for cause of problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我想你正在谈论 ConcurrentModificationException。尝试使用迭代器代替。
I suppose you're talking about ConcurrentModificationException. Try to use iterator instead.
是的,那行不通。
将要删除的所有项目添加到新集合中,然后对原始集合上的这些元素执行
removeAll
操作。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.当您迭代集合时,您无法直接从集合中删除元素 - 这会导致问题,因为迭代器不知道该元素已被删除。
不使用增强的 for 循环,而是直接使用
Iterator
并调用remove()
函数,例如: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 theremove()
function, for example:willcodejavaforfood的答案是这样做的一种方法。
remove
方法,具体取决于样式以及您想在循环中执行的其他操作:另一种选择是显式获取
Iterator
并使用其 当然,只有当您想要从集合中简单删除时才有效。当调用直接从底层集合中删除的潜在复杂方法时,最好的方法是首先获取集合的副本,然后迭代此副本。在所有情况下,在迭代集合时修改集合通常会导致不好的事情发生。
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 itsremove
method: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.