java - 为什么 Java 的 AbstractList 的 removeRange() 方法受到保护?

标签 java list collections arraylist protected

有谁知道,为什么 AbstractList 中的 removeRange 方法(以及在 ArrayList 中)是否受到 protected 的保护?它看起来像是一个定义明确且有用的操作,但仍然要使用它,我们不得不继承 List 实现。

有什么隐藏的理由吗?对我来说似乎很莫名。

最佳答案

是的,因为这不是您从外部代码中删除范围的方式。而是这样做:

list.subList(start, end).clear();

这实际上是在后台调用 removeRange


OP 询问为什么 removeRange 不是 List 公共(public) API 的一部分。原因在 Effective Java 2nd ed 的 Item 40 中有描述,我在这里引用它:

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.

有人可能会争辩说 removeRange 没有那么多参数,因此可能不是这种处理的候选者,但考虑到有一种方法可以通过调用 removeRange subList,没有理由用多余的方法弄乱 List 接口(interface)。


AbstractList.removeRange文档说:

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.

另外,请参阅 OpenJDK 的 AbstractList.clear 实现。和 SubList.removeRange .

关于java - 为什么 Java 的 AbstractList 的 removeRange() 方法受到保护?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2289183/

相关文章:

java - 为什么java.util中没有设置随机访问

java - 将 JComboBox 添加到 JTable 单元格

Java double 到具有特定精度的字符串

Java GC 日志充满了奇怪的字符

python - 在文件名中创建一个以空格分隔的选定字符列表

python - 如何理解Python中list结构的内存?

java - 是否有一个 Java 集合或列表可以在给定对象值的情况下返回对象键?

java - 使用不同名称在循环内创建对象 (JTextfields)

r - 列表元素名称的问题

collections - 正确使用 meteor 包中的集合?