开发者

why is Stack a class while Queue is a Interface? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

I think they are very similar...And when do we need to use sta开发者_如何学Cck or queue, why not just use ArrayList or LinkedList to replace them?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜