I can see in the documentation for:
java.util.AbstractList#removeRange
That it requires quadratic time:
This implementation gets a list iterator positioned before fromIndex,
and repeatedly calls ListIterator.next followed by ListIterator.remove
until the entire range has been removed. Note: if ListIterator.remove
requires linear time, this implementation requires quadratic time.
But why?? The code:
protected void removeRange(int fromIndex, int toIndex) {
ListIterator<E> it = listIterator(fromIndex);
for (int i=0, n=toIndex-fromIndex; i<n; i++) {
it.next();
it.remove();
}
}
Seems for me to be linear… But I have to be wrong as I’m a newbie in this kind of algorithmic stuff. Please help me to understand it.
The reason is in :
that can be an O(n) operation on a list, which you call within an O(n) loop.
In other words, your real loop would look like this if it is the case (I made it up but you get the idea):