Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 934
Yang Avatar asked Jul 16 '11 01:07

Yang


2 Answers

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.

like image 83
Mark Elliot Avatar answered Sep 20 '22 06:09

Mark Elliot


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.

like image 34
Tikhon Jelvis Avatar answered Sep 21 '22 06:09

Tikhon Jelvis