Quick revision
The short answer
After list.remove(i), every later element moves one place to the left, so the next element now sits at index i, but the loop increments i and never looks at it; two zeros in a row leave one behind. We fix it by iterating backwards, by decrementing i after a removal, or simply with list.removeIf(x -> x == 0). On a List<Integer>, remove(i) with an int removes by index, while remove(Integer.valueOf(0)) removes the first element equal to 0, because Java picks the overload that needs no boxing.
What to remember
In this answer, we traced the forward index loop and saw that each remove(i) shifts the next element into index i just as the loop moves on, so adjacent zeros survive. Iterating backwards, stepping i back after a removal, or using removeIf fixes it, with removeIf being the clearest and O(n). We also saw that on a List<Integer>, remove(int) removes by index and remove(Object) by value, because overload resolution prefers the method that needs no boxing, and that == between two Integer objects only works for cached small values.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
After list.remove(i), every later element moves one place to the left, so the next element now sits at index i, but the loop increments i and never looks at it; two zeros in a row leave one behind. We fix it by iterating backwards, by decrementing i after a removal, or simply with list.removeIf(x -> x == 0). On a List<Integer>, remove(i) with an int removes by index, while remove(Integer.valueOf(0)) removes the first element equal to 0, because Java picks the overload that needs no boxing.
Background to this question
This question combines two classic traps in one short loop: the index shift after a removal, and the overloaded remove methods on a list of Integers. Both compile without warnings and both produce wrong results on some inputs only, which is why they survive into production. In this answer, we will trace the loop on a small example to see exactly which zero survives, fix it three ways, then explain how Java chooses between remove(int) and remove(Object), and finish with a note on comparing Integers with ==.
1Tracing the Loop on a Small List
Let us run the loop on a list with two zeros next to each other, and follow i and the list after every step.
| i | Element checked | Action | List afterwards |
|---|---|---|---|
| 0 | 0 | remove(0) | [0, 1, 0] |
| 1 | 1 | keep (skipped the new index 0) | [0, 1, 0] |
| 2 | 0 | remove(2) | [0, 1] |
| 3 | - | loop ends: 3 >= size 2 | [0, 1] |
The reason is the shift. When ArrayList removes the element at index i, it moves every following element one place left to close the gap. The element that was at i + 1 is now at i. But the loop's i++ moves on to i + 1, which now holds what used to be at i + 2. So after every removal, one element is skipped. A single zero is removed correctly; it is two zeros in a row that expose the bug, which is why simple tests often pass.
2Three Ways to Fix the Loop
The first fix is to iterate backwards. Removing at i only shifts elements after i, and we have already visited those, so nothing we still need to check moves.
Decrementing i works too, but changing a loop variable inside the loop is easy to get wrong later. removeIf is the clear winner: it states the intent, it cannot skip anything, and ArrayList implements it in one pass that compacts the survivors once. The two index loops each call remove(i), which shifts the tail of the array every time, so removing many zeros from a long list is O(n squared), while removeIf is O(n).
3Remove(int) Versus remove(Object)
The List interface has two remove methods: remove(int index), which removes the element at a position, and remove(Object o), which removes the first element equal to o. For a List<String> the difference is obvious. For a List<Integer>, both can accept something that looks like a number, so the compiler has to choose.
Java resolves overloads in phases. In the first phase it looks only at methods that fit without boxing or unboxing. list.remove(i) with an int i fits remove(int) directly, so that method wins, and remove(Object) is never considered. list.remove(Integer.valueOf(0)) passes an Integer, which fits remove(Object) directly, so it removes by value.
- Argument is a primitive int?e.g.
list.remove(i)Yesremove(int index): by positionNoArgument is an Integer or Object - remove(Object o)removes the first element where
equals(o)is true - Returnsremoved element for
remove(int), boolean forremove(Object)
3 steps in order. Play them, or step through them one at a time.
Notice the last line. A developer who means remove the value 5 and writes remove(5) gets an exception if the list is short, or silently removes the wrong element if it is long enough. Whenever we remove by value from a list of Integers, we write Integer.valueOf(x) or cast to Object, so the intent is explicit.
4A Note on Comparing Integers With ==
The loop in the question compares list.get(i) == 0. Here the right-hand side is an int, so Java unboxes the Integer and compares numbers, and the comparison is correct (it would throw NullPointerException on a null element). The trap appears when both sides are Integer objects: then == compares references, not values.
Integer.valueOf, which autoboxing uses, returns cached objects for -128 to 127, so == between two Integers appears to work for small numbers in tests and fails for larger ones in production. The safe habit is to compare Integer objects with equals() or to unbox explicitly, and to use == only when at least one side is a primitive.
5Follow-up questions
Would a for-each loop with list.remove(Integer.valueOf(0)) work instead?
No. Removing through the list during for-each changes its modCount, and the iterator's next step throws ConcurrentModificationException, or, if the removed element was second-last, ends early and skips the last one. Use removeIf or an explicit Iterator with it.remove().
How do we remove all zeros, not just the first, by value?
list.removeIf(x -> x == 0) is the clearest. list.removeAll(List.of(0)) also removes every element equal to 0, using equals(). A loop of remove(Integer.valueOf(0)) until it returns false works but scans the list from the start each time, which is O(n squared).
Why does the backwards loop not skip anything?
Removing at index i shifts only the elements after i, and a backwards loop has already visited all of them. The next index it looks at, i - 1, is unaffected by the removal, so every element is checked exactly once.
6Conclusion
In this answer, we traced the forward index loop and saw that each remove(i) shifts the next element into index i just as the loop moves on, so adjacent zeros survive. Iterating backwards, stepping i back after a removal, or using removeIf fixes it, with removeIf being the clearest and O(n). We also saw that on a List<Integer>, remove(int) removes by index and remove(Object) by value, because overload resolution prefers the method that needs no boxing, and that == between two Integer objects only works for cached small values.
Open with
The loop skips elements. When I call remove(i) on an ArrayList, everything after i shifts one place left, so the next element is now at index i, but the loop does i++ and moves past it.
Then, if they want more
With the list 0, 0, 1, 0, the first zero is removed, the second zero slides into index 0, and the loop never sees it, so the result is 0, 1. A single zero works, which is why tests often miss it. There are three fixes. Iterate backwards, because removing at i only shifts elements I have already checked.
Or decrement i after removing, which works but is fragile. Or, what I would actually write, list.removeIf(x -> x == 0), which states the intent, cannot skip, and on ArrayList runs in a single pass, whereas repeated remove calls shift the array each time and become quadratic. On the second part, List has two removes: remove(int index) and remove(Object).
For a List of Integer, the compiler first looks for a method that needs no boxing, so remove with an int argument removes by position, while remove(Integer.valueOf(0)) removes the first element equal to zero. That is why list.remove(5) can throw IndexOutOfBounds when you meant the value five.
Finally, in this loop get(i) == 0 is fine because the int literal forces unboxing, but comparing two Integer objects with == only works for cached values from minus 128 to 127, so I use equals.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Collections Framework, overview, java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "This index loop does not remove all zeros:": https://scrivio-interview-library.netlify.app/java/lists/7c6a4e2e70/