我陷入了一种非常奇怪的情况..那是有两个嵌套的for循环,最里面的for循环我正在测试一些条件,如果该条件成立,那么在该状态下,我会使用内部for循环,同时通过使用Continue语句从该索引本身的数组列表中删除元素,但现在我希望相同的最内部for循环继续数组列表的下一个剩余元素,但现在它没有发生......现在实际发生了什么,现在如果条件在内部for循环中为真,那么元素该索引将从数组列表中删除 然后流程转到 continue 语句,该语句再次将流程转移到内部 for 循环的开头,这是完美的,但从那里开始,现在从内部 for 循环开始的流程应该进入 for 循环内部,但没有发生
根据我的分析,当我在产生问题的内部 for 循环中条件变为 true 时,从列表中删除元素 请告知,因为 continue 再次将流程返回到内部 for 循环的乞求,然后从那里开始流程进入内部 for 循环的末尾,这不应该发生,它应该进入 for 循环内部以获取剩余的 arraylist 元素,请告知
//outermost for loop
for (File file : updatedFile) {
//fetching data into the list
List<teetobjects> abcobjects = (List<teetobjects>) feedObjectsGetter.getObjects(file);
//inner most for loop begains
for (teetobjects pecdeedObject : abcobjects) {
//checking some condition for each element in the inner most element ....
if (st.contains(s1)) {
// if the condition is true then removing the element of the
// aaraylist named abcobjects within inner for loop
abcobjects.remove(recFeedObject);
continue;
}
}
}
最佳答案
您无法使用 for
的“foreach”版本从正在迭代的容器中删除对象。循环:如果从正在迭代的集合中删除一个对象,您将得到 ConcurrentModificationException
.
为了使其工作,您需要使用 ListIterator<T>
明确地,并调用 remove
关于它:
List<teetobjects> abcobjects = (List<teetobjects>)feedObjectsGetter.getObjects(file);
//inner most for loop begins
ListIterator<teetobjects> iter = abcobjects.listIterator();
while (iter.hasNext()) {
teetobjects pecdeedObject = iter.next();
//checking some condition for each element in the inner most element ....
if (st.contains(s1)) {
// if the condition is true then removing the element of the
// aaraylist named abcobjects within inner for loop
iter.remove();
continue;
}
}
关于java - 遍历最内层 for 循环内的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23412536/