为什么 LinkedHashSet 没有 addFirst 方法?

Why doesn't LinkedHashSet have addFirst method?

正如 LinkedHashSet 的文档所述,它是

Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries.

所以它本质上是一个 HashSet 具有由链表实现的键的 FIFO 队列。考虑到 LinkedListDeque 并且允许,特别是在开头插入,我想知道为什么 LinkedHashSet 除了存在的方法之外没有 addFirst(E e) 方法Set 界面。实现起来似乎并不难。

正如 Eliott Frisch 所说,答案在您引用的段落的下一句中:

… This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). …

addFirst 方法会破坏插入顺序,从而破坏 LinkedHashSet 的设计思想。

如果我也可以添加一些猜测,其他可能的原因可能包括:

  • 实现起来并不像看起来那么简单,因为 LinkedHashSet 实际上是作为 LinkedHasMap 实现的,其中不使用映射到的值。至少你也必须改变 class (这反过来也会破坏 它的 插入顺序,从而破坏它的设计理念)。
  • 正如其他人在评论中的意图,他们认为它没有用。

就是说,您问的问题是错误的。他们设计了一个 class 具有他们认为需要的功能。他们继续使用哈希 table 和链表来实现它。您从实施开始并将其用作设计讨论的基础。虽然这偶尔会增加一些有用的东西,但通常这不是好的设计的方式。

虽然理论上我可以理解您的观点,即在某些情况下您可能需要一个带有集合 属性 的双端队列(重复项为 ignored/eliminated),但我很难想象当 Deque 在这种情况下无法满足您的需求时(Eliott Frisch 提到未充分利用的 ArrayDeque)。在 containsremove 的线性复杂性令人望而却步之前,您需要相当大量的数据 and/or 非常严格的性能要求。在那种情况下,您可能已经更好地自定义设计自己的数据结构。