Why is Java's AbstractList's removeRange() method protected?

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.

35245 次浏览

Yes, because that's not how you remove a range from outside code. Instead, do this:

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

这实际上在幕后调用 removeRange


OP 询问为什么 removeRange不是 List公共 API 的一部分。原因在《有效的 Java 第二版》第40条中有描述,我在这里引用它:

有三种方法可以缩短过长的参数列表。一种是将方法分解为多个方法,每个方法只需要参数的一个子集。如果不小心,这可能导致太多的方法,但它也可以帮助 减少的方法计数增加正交。例如,考虑 java.util.List接口。它不提供查找子列表中元素的第一个或最后一个索引的方法,这两个方法都需要三个参数。相反,它提供了 subList方法,该方法接受两个参数并返回子列表的 风景。这种方法可以与 indexOflastIndexOf方法结合使用,每个方法都有一个参数,从而产生所需的功能。此外,subList方法还可以与操作 List实例的 任何方法相结合,在子列表上执行任意计算。由此产生的 API 具有很高的功率重量比。

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


? AbstractList.removeRange文件说:

此方法由此列表及其子列表上的 clear操作调用。重写此方法以利用列表实现的内部结构可以提高 实质上对此列表及其子列表的 clear操作的性能。

另外,请参阅 OpenJDK 对 AbstractList.clearSubList.removeRange的实现。