Search code examples
javalisteffective-java

What is the use of removeRange method of AbstractList class in subclasses


In Effective Java, it is stated that

removeRange method is of no interest to end users of a List implementation. It is provided solely to make it easy for subclasses to provide a fast clear method on sublists. In the absence of the removeRange method, subclasses would have to make do with quadratic performance when the clear method was invoked on sublists or rewrite the entire subList mechanism from scratch—not an easy task!

Please have a look at this link. Last paragraph. It says In the absence of the removeRange method, subclasses would have to make do with quadratic performance.

Please explain why author said this.


Solution

  • The AbstractList already provides a default implementation of subList(int from, int to). The clear() method of this default sub-list simply calls removeRange(...) on its parent list.

    Without removeRange(...), the sub-list would have to use an iterator, calling next() and remove() repeatedly. But removing elements via Iterator.remove() might have linear performance - e.g. ArrayList has to left-shift all subsequent elements in its internal array every time an element is removed. Calling a linear method repeatedly results in a quadratic performance.

    Note: The removeRange(...) implementation in AbstractList uses an iterator by default. So subclasses should override it to provide a more performant implementation (if available).

    The advantage: To optimize performance, subclasses have to implement removeRange only, and they can keep the default implementation of subList(...).