For completeness’ sake, although I prefer backwards
loops for deleting elements, here’s how to do the same w/ a forward
loop the right way: ![]()
final IntList nums = IntList.fromRange(10);
println(nums);
println("Forwards:");
for(int i = 0; i < nums.size(); ++i) {
println("index:", i, TAB, "value:", nums.get(i));
nums.remove(i--);
}
println(nums);
exit();
B/c we’re emptying the whole container, the index i is stuck at value 0 on all iterations. ![]()
Here’s the same example; but this time we’re sparing the indices containing the values 5 & 8: ![]()
final IntList nums = IntList.fromRange(10);
println(nums);
println("Forwards:");
for (int i = 0; i < nums.size(); ++i) {
final int val = nums.get(i);
println("index:", i, TAB, "value:", val);
if (val != 5 & val != 8) nums.remove(i--);
}
println(nums);
exit();
The index i ends up w/ value 2; b/c that’s how many indices which has been spared. ![]()