Why is removeRange(int fromIndex, int toIndex) in Java Vector is protected?

284 views Asked by At

can anyone throw some light on why is removeRange(int fromIndex, int toIndex) in Java Vector is protected?

Syntax - protected synchronized void removeRange(int fromIndex, int toIndex)

I have studies a few blogs and did some code to understand but things are not really clear here. I have looked inside Vector.java and tried to create some understanding as well. But my overall perception is that removeRange(int fromIndex, int toIndex) will eventually get removed.

I felt sublist(int fromIndex, int toIndex).clear() is capable of doing the same job. And looks more apt from implementation and usability point of view.

Please help in understanding if you have a better thought.

1

There are 1 answers

5
Hulk On BEST ANSWER

It is there because it is inherited form AbstractList.removeRange. The intention for exposing it in this abstract base class is documented as enabling subclasses to improve the performance of clear():

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.

It is extremely unlikely that this method will ever be removed, as this would be a major compatibility problem.

But you are right that as a user of this class you should stick with the public interface, the protected methods are mostly useful for implementing subclasses.


So, why is the method not made public?

The JavaDocs for List.subList tell us

This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a list can be used as a range operation by passing a subList view instead of a whole list. For example, the following idiom removes a range of elements from a list:

 list.subList(from, to).clear();

So not including range operations in the public interface was a deliberate design choice. On any List implementation, these operations can be performed by invoking operations on sublist views.