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.
The removeRange() method is protected . This means it can only be accessed within the class/package/subclass. This is why the Main method extends the ArrayList class in the above example. Since the Main class inherits all properties of the ArrayList , we can create the arraylist using the Main class.
The removeRange() method is used to removes all elements within the specified range from a ArrayList object. It shifts any succeeding elements to the left (reduces their index). This call shortens the list by (toIndex - fromIndex) elements.
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 thesubList
method, which takes two parameters and returns a view of a sublist. This method can be combined with theindexOf
orlastIndexOf
methods, each of which has a single parameter, to yield the desired functionality. Moreover, thesubList
method can be combined with any method that operates on aList
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 theclear
operation on this list and its subLists.
Also, see OpenJDK's implementation of AbstractList.clear
and SubList.removeRange
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With