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

Solution 1:

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.