Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, why is it that a Stack is a concrete class whereas the Queue is an interface?

Tags:

stack

queue

Which one of Queue's subclasses is a 'plain ordinary' queue?

like image 547
tomejuan Avatar asked Apr 04 '11 02:04

tomejuan


People also ask

Why is Queue an interface but stack a class in Java?

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.

Is stack a concrete class in Java?

In Java, why is it that a Stack is a concrete class whereas the Queue is an interface? - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.

Is stack an interface in Java?

The Stack data structure is based on the Last In First Out (LIFO) principle and in Java, it implements the Java List interface.

Why is stack a class in Java?

In Java, Stack is a class that falls under the Collection framework that extends the Vector class. It also implements interfaces List, Collection, Iterable, Cloneable, Serializable. It represents the LIFO stack of objects. Before using the Stack class, we must import the java.


1 Answers

(1) java.util.Stack is a legacy class from Java 1.0. It predates the Collections framework by many years, and it's frankly an example of horrible design on many fronts. Nothing about it is the way things should be. The main problem is that Stack extends Vector, and as all inheritance in Java is public inheritance, all the methods of Vector are available on Stack as well. Therefore, you can inspect any position in a Stack, add and remove elements from the middle, clear it, or do any number of other things that should not be part of a stack abstraction, without a cast. Contrast that to using the Queue or Deque interfaces, through which only stack-appropriate methods are available.

(2) There really is no such thing as a plain ordinary queue, but LinkedList implements Queue without any special semantics, so maybe that's what you want.

like image 200
Ernest Friedman-Hill Avatar answered Oct 19 '22 10:10

Ernest Friedman-Hill