gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 11:29:32 26 4
gpt4 key购买 nike

有谁知道,为什么 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com