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?
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
; Queue
s and List
s 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.
Stack
s should be used when you need LIFO semantics, while Queue
s 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. Stack
s and Queue
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With