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();
}
IMPORTANT NOTE: passTest(curInt)
logic can be different for each iteration. It means that iteration one can cause continue
, then the second and third iterations will cause a removal. PROBLEM is I'm expecting for a fourth iteration (on the first item that wasn't removed).
The solution I've found:
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();
}
Is that the right way to achieve that?
Your solution doesn't seem correct. You will first iterate over all the elements of the List
, possibly removing some of them. Once you finish iterating over the List
, iteration.hasNext()
will always return false
, so you'll keep getting the first element (due to curInt = lst.get(0)
). If you remove that first element, you'll get a different element the next time curInt = lst.get(0)
is executed, so the List
will become empty in the end, but that doesn't seem like the desired behavior (if it was the desired behavior, you could eliminate the Iterator
and just keep getting the first element in a loop and possibly removing it).
You should use nested loops, and re-create the Iterator
instance inside the outer loop:
while (!lst.isEmpty()) {
Iteartor<Integer> iterator = lst.listIterator();
while (iterator.hasNext()) {
Integer curInt = iterator.next();
if (passTest(curInt)) {
iterator.remove();
}
}
}
Each iteration of the outer loop creates an Iterator
and performs the inner loop.
Each iteration of the inner loop iterates over the elements of the List
, and possibly removes some of them.
Once you finish an iteration over the List
, you must create a new Iterator
in order to iterate over the remaining elements again.