0

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.

Community
  • 1
  • 1
user961690
  • 698
  • 1
  • 11
  • 22

2 Answers2

1

In the absence of the removeRange method, subclasses would have to make do with quadratic performance when the clear method was invoked on sublists

The author makes an assumption that implementations would have to call remove for each element of a range. In some implementations, such as ArrayLists, remove must copy everything after the element being removed, which has O(n) complexity. Assuming that the range size is r, the overall complexity of a loop implementation would be O(n*r), which is quadratic.

An implementation of removeRange specific to ArrayList has O(n) complexity, because you can copy the to its new position in a single loop.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Sorry Sir, I could not accept your answer. But please believe me your answer is as brilliant as the answer I accepted. I will go through the questions you answered and award you +25 or more immediately. Thanks – user961690 Mar 31 '15 at 13:53
1

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(...).

isnot2bad
  • 24,105
  • 2
  • 29
  • 50