22

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?

Yang
  • 406
  • 3
  • 9
  • 1
    You should read a good data structures book. Briefly: The restrictions can improve performance and increase simplicity of understanding the code. – Merlyn Morgan-Graham Jul 16 '11 at 01:04
  • 3
    Because the designers of Java suck at APIs. Stack **should** have been an interface, so there can be different implementations of stacks. For example an array-list based stack and a linked-list based stack. Instead, they took a shortcut and subclassed Vector to make some sort of franken-stack that exposes a lot of incorrect implementation details of its parent. They made an attempt to correct this by creating a Deque (ie another stack implementation) but just created more confusion. – Evan Plaice Feb 16 '14 at 22:05

2 Answers2

7

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.

Tikhon Jelvis
  • 67,485
  • 18
  • 177
  • 214
7

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.

Mark Elliot
  • 75,278
  • 22
  • 140
  • 160