为什么Stack是一个类而Queue是一个接口?

发布于 2024-11-24 01:34:47 字数 74 浏览 1 评论 0原文

我认为它们非常相似......而我们什么时候需要使用堆栈或队列,为什么不直接使用ArrayList或LinkedList来代替它们呢?

I think they are very similar...And when do we need to use stack or queue, why not just use ArrayList or LinkedList to replace them?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦行七里 2024-12-01 01:34:48

Stack 是一个后进先出的对象堆栈,派生自 Vector,也是一个类。 Vector 与 Java 最初附带的“旧”集合集一起使用,并最终派生自 AbstractCollection。值得注意的是,实际上有一个 Stack 的规范实现; QueueList许多众所周知的实现,如果选择正确,可以产生显着的性能差异。

另一方面,Queue 遵循当今通常使用的“新”集合集中的 Collection 接口,因此它遵循这些接口并附带各种实现。

当您需要 LIFO 语义时,应使用Stack,而当您需要先进先出语义时,应使用Queue

ArrayListLinkedList 存储有序的事物集合,并且不符合 Stack 的用例或直接队列StackQueue 在某种意义上是数据缓冲区,而 List 的语义通常使其成为数据存储;没有什么可以阻止您使用List来实现StackQueue

Stack, is a Last-In-First-Out stack of objects derived from Vector, also a class. Vector goes with the "old" set of collections that Java originally shipped with, and derives ultimately from AbstractCollection. Of note, there's really one canonical implementation of a Stack; Queues and Lists have many well known implementations that can make a substantial performance difference when chosen correctly.

Queue on the other hand follows the Collection interface from the "new" set of collections that are typically used today, so it follows the interfaces and comes with a variety of implementations.

Stacks should be used when you need LIFO semantics, while Queues should be used when you need First-In-First-Out semantics.

ArrayList and LinkedList store ordered collections of things, and don't line up with the use-cases of Stack or Queue directly. Stacks and Queues are in a sense buffers of data, whereas the semantics of a List typically make it such that it's a store of data; nothing is stopping you from using a List to implement a Stack or a Queue.

就像说晚安 2024-12-01 01:34:48

原因之一是队列有多种变体可以方便地交换,例如 PriorityQueue。它们实现相同的接口,但行为不同。我认为 Stacks 没有类似的东西,或者至少它的使用频率不那么高。

您无法仅使用 ArrayList 来模拟优先级队列。

此外,关于第二个问题,当您在语义上使用堆栈或队列时,您可能应该使用堆栈或队列。也就是说,如果您正在执行图形遍历之类的操作,那么非常明确地了解您正在使用的数据结构类型会很有帮助。

Well, one reason is that there are variants of Queues that it is convenient to be able to swap in, like PriorityQueues. They fulfill the same interface but behave differently. I don't think there is anything like that for Stacks, or at least it isn't used nearly as often.

You would not be able to simulate a Priority Queue using just an ArrayList.

Additionally, regarding your second question, you should probably use a stack or queue when that is what you're using semantically. That is, if you are doing something like graph traversal, it helps to be very explicit about the sort of data structure you're using.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文