Ron*_*erg 4 java iterator loops list empty-list
I'm trying to iterate a list, wherein each iteration I'm doing one of the below:
What I need is that after I'm iterating through all the items, it will continue to iterate until the list is empty (the logic ensures all elements will be removed).
Problem is that after the iterator iterates all the list elements, it didn't continue to run on the elements I didn't remove:
List<Integer> lst = new ArrayList();
lst.add(1);
lst.add(2);
lst.add(3);
Iteartor<Integer> iterator = lst.listIterator();
while (iterator.hasNext()){
Integer curInt = iterator.next();
if (!passTest(curInt)){
continue;
}
iterator.remove();
}
Run Code Online (Sandbox Code Playgroud)
重要说明:passTest(curInt)每次迭代的逻辑可以不同。这意味着一次迭代可以导致continue,然后第二次和第三次迭代将导致删除。问题是我期望进行第四次迭代(在未删除的第一项上)。
我找到的解决方案:
List<Integer> lst = new ArrayList();
lst.add(1);
lst.add(2);
lst.add(3);
Iteartor<Integer> iterator = lst.listIterator();
while (!lst.isEmpty()){
Integer curInt;
if (iteration.hasNext()){
curInt = iterator.next();
} else {
curInt = lst.get(0);
}
if (!passTest(curInt)){
continue;
}
iterator.remove();
}
Run Code Online (Sandbox Code Playgroud)
那是实现这一目标的正确方法吗?
您的解决方案似乎不正确。您将首先遍历的所有元素List,可能会删除其中的一些元素。一旦完成对的迭代List,iteration.hasNext()它将始终返回false,因此您将继续获取第一个元素(由于curInt = lst.get(0))。如果删除了第一个元素,则下次curInt = lst.get(0)执行时将获得另一个元素,因此最后List将变为空,但这似乎不是所需的行为(如果是所需的行为,则可以消除的Iterator,只是不断收到在一个循环中的第一个元素,并可能移除它)。
您应该使用嵌套循环,并Iterator在外部循环内重新创建实例:
while (!lst.isEmpty()) {
Iteartor<Integer> iterator = lst.listIterator();
while (iterator.hasNext()) {
Integer curInt = iterator.next();
if (passTest(curInt)) {
iterator.remove();
}
}
}
Run Code Online (Sandbox Code Playgroud)
外循环的每次迭代都会创建一个Iterator并执行内循环。
内部循环的每次迭代都会迭代的元素List,并可能删除其中的一些元素。
完成对的迭代后List,您必须创建一个新对象Iterator以再次遍历其余元素。