为什么Java的AbstractList的removeRange()方法受到保护?
有谁知道为什么的removeRange方法“noreferrer">AbstractList(也在 ArrayList) 是否受保护
?它看起来是一个定义良好且有用的操作,但为了使用它,我们不得不对 List 实现进行子类化。
难道有什么隐藏的道理吗?对我来说似乎很莫名其妙。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,因为这不是从外部代码中删除范围的方式。相反,这样做:
这实际上在幕后调用
removeRange
。†OP 询问为什么
removeRange
不是List< 的一部分/code> 公共 API。原因在Effective Java 2nd ed的Item 40中有描述,我在这里引用一下:
有人可能会说
removeRange
没有那么多参数,因此可能不适合这种处理,但考虑到有一种方法可以通过removeRange
调用removeRange
>subList,没有理由用冗余的方法使List
接口变得混乱。†
AbstractList.removeRange
文档说:另请参阅 OpenJDK 的
AbstractList.clear
和SubList.removeRange
。Yes, because that's not how you remove a range from outside code. Instead, do this:
This actually calls
removeRange
behind the scenes.†The OP asks why
removeRange
is not part of theList
public API. The reason is described in Item 40 of Effective Java 2nd ed, and I quote it here:One can argue that
removeRange
doesn't have that many parameters and is therefore probably not a candidate for this treatment, but given that there's a way to invokeremoveRange
through thesubList
, there is no reason to clutter up theList
interface with a redundant method.† The
AbstractList.removeRange
documentation says:Also, see OpenJDK's implementation of
AbstractList.clear
andSubList.removeRange
.