Task 7 of 11 · 0 solved · 11 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

5.3 Lists — removing while looping

Lesson

Ловушка, которая молчит

Removing an element while walking forward through a list skips elements — and the program does not crash, so the bug hides. Every removal shifts the rest left by one, while the loop counter still moves right.


Смотрите сами

// list is [1, 2, 2, 3], remove every 2
for (int i = 0; i < list.size(); i++) {
    if (list.get(i) == 2) { list.remove(i); }
}
// result: [1, 2, 3]  — one 2 survived!

After removing the first 2, the second 2 slid into its place — but i had already moved past it.

The fix: walk backwards. Removals then shift only the part you have already visited:

for (int i = list.size() - 1; i >= 0; i--) {
    if (list.get(i) == 2) { list.remove(i); }
}
// result: [1, 3]

▶ Try it: run this, then change something and run it again.



Removing while walking forward...


Why does walking backwards fix it?


Type exactly what this program prints.

import java.util.ArrayList;

public class Main { public static void main(String[] a){
    ArrayList<Integer> l = new ArrayList<Integer>();
    l.add(5); l.add(5); l.add(7);
    for (int i = l.size() - 1; i >= 0; i--) {
        if (l.get(i) == 5) {
            l.remove(i);
        }
    }
    System.out.println(l);
}}

What makes this bug dangerous?


True or false?