为什么 Java Vector 中的 removeRange(int fromIndex, int toIndex) 受到保护?

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

谁能解释一下为什么 Java 中的 removeRange(int fromIndex, int toIndex) 向量受到保护?

语法 - protected synchronized void removeRange(int fromIndex, int toIndex)

我研究了一些博客并做了一些代码来理解,但这里的事情并不是很清楚。我查看了内部 Vector.java 并试图建立一些理解。但我的总体看法是 removeRange(int fromIndex, int toIndex) 最终会被删除。

我觉得 sublist(int fromIndex, int toIndex).clear() 有能力做同样的工作。从实施和可用性的角度来看,看起来更合适。

如有更好的想法请帮忙理解

它在那里是因为它是从 AbstractList.removeRange 继承而来的。在这个抽象基础 class 中公开它的意图被记录为启用 subclasses 以提高 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.

极不可能删除此方法,因为这将是一个主要的兼容性问题。

但是你是对的,作为这个 class 的用户你应该坚持使用 public 接口,受保护的方法主要用于实现 subclasses。


所以,为什么方法没有制作public?

List.subList 的 JavaDocs 告诉我们

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();

因此,在 public 界面中不包括范围操作是一种深思熟虑的设计选择。在任何 List 实现中,这些操作都可以通过调用子列表视图上的操作来执行。