The problem with removing element i
with the above code is that you'd skip elements.
For the following, I assume this "corrected" code:
for(int i = 0; i<arrayList.size(); i++)
arrayList.remove( i );
Assume a list with elements "a","b","c","d"
.
Now let's check the iterations:
i = 0
and arrayList.size() = 4
-> we remove the element at index 0 which is "a"
i = 1
and arrayList.size() = 3
-> we remove the element at index 1 which is "c"
(index 0 is "b"
)
i = 2
and arrayList.size() = 2
-> we stop
There are two ways to solve that:
- never increment
i
, i.e. it will always be 0 (Edit: in that case you could just use a while-loop with the condition arrayList.size() > 0
and always remove the first element, i.e. remove(0)
)
- remove backwards, i.e. start at
arrayList.size() - 1
and decrement i
until you reach a value lower than 0.
If you're using foreach (i.e. you implicitly use an iterator) then calling remove(i)
with any value will result in a ConcurrentModificationException
since you could basically do something similar as I depicted above (skipping elements) and thus the iterator checks for any modifications while iterating (normally done by a modification counter in the list and a snapshot of the value in the iterator).
Using an explicit iterator (i.e. for( Iterator<String> itr = arrayList.iterator(); ...
) and calling remove()
on the iterator will prevent that since the iterator as well as the list are notified of the modification and can react to it properly.