views:

363

answers:

1

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.

+6  A: 

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.

Chris Jester-Young
Ok, it can done that way, but *why*? Seems awkward. Single elements can be removed from the list directly, why not multiple elements then?
Joonas Pulakka
@Joonas: Item 40 of Effective Java, 2nd ed describes the rationale for this. I'll paste in the relevant section in case you don't have the book.
Chris Jester-Young
Thanks, exactly what I was looking for! Now it makes *some* sense :)
Joonas Pulakka
Very nicely answered, Chris.
Kevin Bourrillion