Why is Java's AbstractList's removeRange() method protected?

JavaListCollectionsArraylistProtected

Java Problem Overview


Does anyone have any idea, why removeRange method in AbstractList (and also in ArrayList) is protected? It looks like a quite well-defined and useful operation, but still, to use it, we're forced to subclass the List implementation.

Is there some hidden rationale? Seems quite inexplicable to me.

Java Solutions


Solution 1 - Java

Yes, because that's not how you remove a range from outside code. Instead, do this:

list.subList(start, end).clear();

This actually calls removeRange behind the scenes.


The OP asks why removeRange is not part of the List public API. The reason is described in Item 40 of Effective Java 2nd ed, and I quote it here:

> There are three techniques for shortening overly long parameter lists. One is to break the method up into multiple methods, each of which requires only a subset of the parameters. If done carelessly, this can lead to too many methods, but it can also help reduce the method count by increasing orthogonality. For example, consider the java.util.List interface. It does not provide methods to find the first or last index of an element in a sublist, both of which would require three parameters. Instead it provides the subList method, which takes two parameters and returns a view of a sublist. This method can be combined with the indexOf or lastIndexOf methods, each of which has a single parameter, to yield the desired functionality. Moreover, the subList method can be combined with any method that operates on a List instance to perform arbitrary computations on sublists. The resulting API has a very high power-to-weight ratio.

One can argue that removeRange doesn't have that many parameters and is therefore probably not a candidate for this treatment, but given that there's a way to invoke removeRange through the subList, there is no reason to clutter up the List interface with a redundant method.


The AbstractList.removeRange documentation says:

> This method is called by the clear operation on this list and its subLists. Overriding this method to take advantage of the internals of the list implementation can substantially improve the performance of the clear operation on this list and its subLists.

Also, see OpenJDK's implementation of AbstractList.clear and SubList.removeRange.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoonas PulakkaView Question on Stackoverflow
Solution 1 - JavaChris Jester-YoungView Answer on Stackoverflow