All the 0’s will not be removed (which is your intention).
After the first iteration, your list will be [0, 4, 2, 5, 0, 3, 0]
.
Now, k=1
. You will only be looking from the element 4
at index = 1.
Instead, try using Iterators:
Example:
for (Iterator<String> iter = list.iterator(); iter.hasNext();) {
String s = iter.next();
if (s.equals("to_remove")) {
iter.remove();
}
}
1
solved ArrayList remove methods [closed]