Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can we instantiate a stack but not a queue?

Tags:

java

stack

queue

Why I can instantiate a stack like this:

Stack<Integer> stack = new Stack<>();

But can't instantiate a queue like this:

Queue<Integer> queue = new Queue<>();

Is that because queue is a interface while stack is a object? If so, why we say that everything in java is an object?

like image 630
user5516371 Avatar asked Feb 08 '23 22:02

user5516371


1 Answers

A Queue is an interface, meaning we cannot construct a Queue directly.

We can create object using implementing classes, implements the Queue interface, like one of the following: AbstractQueue, ArrayBlockingQueue, ConcurrentLinkedQueue, DelayQueue, LinkedBlockingQueue, LinkedList, PriorityBlockingQueue, PriorityQueue, or SynchronousQueue.

Stack is the class and can be instantiated directly.

This is by design and with Queue, lot more options are there using implementing classes.

like image 140
Ankur Singhal Avatar answered Feb 12 '23 10:02

Ankur Singhal