I'm assuming that mapOverlays
holds an ArrayList
reference.
If mapOverlays
is declared as a List
or ArrayList
, then mapOverlays.remove(n)
will refer to the remove(int)
method that removes the object at a given offset. (So far so good ...)
When you remove the nth
element of an array using remove(int)
, the elements starting at position n + 1
and above all get moved down by one. So what you are doing won't actually work in most cases. (In fact, you are likely to remove about half of the elements you want to remove, and then get an IndexOutOfBoundsException
.)
The best solution is either:
for (int i = size - 1; i > 0; i--) {
mapOverlays.remove(i);
}
or
tmp = mapOverlays.remove(0);
mapOverlays.clear();
mapOverlays.add(tmp);
(Note that the first solution always removes from the end of the list, avoiding the need to copy elements to fill in the hole left by the removed element. The performance different is significant for a large ArrayList.)
However, if mapOverlays
is declared as a Collection
, remove(n)
will bind to the remove(<E>)
overload which removes the object that matches its argument. Depending on the declared type, this will either give you a compilation error, or the int
will be autoboxed as an Integer
and you (probably) won't remove anything. GOTCHA!