gpt4 book ai didi

java - 为什么Java List接口(interface)不支持getLast()?

转载 作者:太空狗 更新时间:2023-10-29 22:33:21 25 4
gpt4 key购买 nike

我正在尝试了解 Java 标准集合库中 API 的不一致。

List 或 AbstractList 中没有获取最后一项的方法,尽管可以使用 size 和 getIndex() 来模拟它。

但是,LinkedList 支持该功能。

知道为什么决定不在界面中支持此方法吗?

最佳答案

java.util.List 接口(interface)不支持 getLast(),因为设计者追求的是“最小接口(interface)”。由于定义的方法数量最少,因此更容易理解和更快地学习。

这与“人性化界面”(例如在 Ruby array class 中使用的界面)形成对比,后者试图提供执行常见操作的方法(例如 getLast())。由于可以将诸如列表这样的基本概念用于许多用途,因此往往会导致更大的界面。

有关更多信息,请参阅 Martin Fowler 的 Minimal InterfaceHumane Interface说明。

关于LinkedList为什么支持getLast()等,引用javadoc:

... the LinkedList class provides uniformly named methods to get, remove and insert an element at the beginning and end of the list. These operations allow linked lists to be used as a stack, queue, or double-ended queue (deque).

据推测,人们认为通用列表不足以满足这些特定用例。

作为对 Java Collections API 主要设计者 (Joshua Bloch) 思想的洞察,他提供了 this list of API design maxims他工作的方式。其中,与这个问题最相关的是:

Early drafts of APIs should be short, typically one page with class and method signatures and one-line descriptions. This makes it easy to restructure the API when you don't get it right the first time.

When in doubt, leave it out. If there is a fundamental theorem of API design, this is it. It applies equally to functionality, classes, methods, and parameters. Every facet of an API should be as small as possible, but no smaller. You can always add things later, but you can't take them away. Minimizing conceptual weight is more important than class- or method-count.

Keep APIs free of implementations details. They confuse users and inhibit the flexibility to evolve. It isn't always obvious what's an implementation detail: Be wary of overspecification.

Minimize accessibility; when in doubt, make it private. This simplifies APIs and reduces coupling.

Consider the performance consequences of API design decisions, but don't warp an API to achieve performance gains. Luckily, good APIs typically lend themselves to fast implementations.

不过他还说:

Don't make the client do anything the library could do. Violating this rule leads to boilerplate code in the client, which is annoying and error-prone.

这表明设计指南经常会发生冲突,而 API 设计人员工作中最困难的部分就是平衡这些冲突。

关于java - 为什么Java List接口(interface)不支持getLast()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1049518/

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