为什么Stack是一个类而Queue是一个接口?
我认为它们非常相似......而我们什么时候需要使用堆栈或队列,为什么不直接使用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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Stack
是一个后进先出的对象堆栈,派生自Vector
,也是一个类。Vector
与 Java 最初附带的“旧”集合集一起使用,并最终派生自AbstractCollection
。值得注意的是,实际上有一个Stack
的规范实现;Queue
和List
有许多众所周知的实现,如果选择正确,可以产生显着的性能差异。另一方面,
Queue
遵循当今通常使用的“新”集合集中的Collection
接口,因此它遵循这些接口并附带各种实现。当您需要 LIFO 语义时,应使用
Stack
,而当您需要先进先出语义时,应使用Queue
。ArrayList
和LinkedList
存储有序的事物集合,并且不符合Stack
的用例或直接队列
。Stack
和Queue
在某种意义上是数据缓冲区,而List
的语义通常使其成为数据存储;没有什么可以阻止您使用List
来实现Stack
或Queue
。Stack
, is a Last-In-First-Out stack of objects derived fromVector
, also a class.Vector
goes with the "old" set of collections that Java originally shipped with, and derives ultimately fromAbstractCollection
. Of note, there's really one canonical implementation of aStack
;Queue
s andList
s have many well known implementations that can make a substantial performance difference when chosen correctly.Queue
on the other hand follows theCollection
interface from the "new" set of collections that are typically used today, so it follows the interfaces and comes with a variety of implementations.Stack
s should be used when you need LIFO semantics, whileQueue
s should be used when you need First-In-First-Out semantics.ArrayList
andLinkedList
store ordered collections of things, and don't line up with the use-cases ofStack
orQueue
directly.Stack
s andQueue
s are in a sense buffers of data, whereas the semantics of aList
typically make it such that it's a store of data; nothing is stopping you from using aList
to implement aStack
or aQueue
.原因之一是队列有多种变体可以方便地交换,例如 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.