P R
P R

Reputation: 1301

Java Stack Linked list

I have declared a Queue of objects Node with the following lines of code:

Queue<Node> queue;
queue = new LinkedList<Node>();

However, when I declare a stack of the Node objects, by replacing the Queue with stack, it doesn't work. Why is it so? Also, what exactly does

queue = new LinkedList<Node>(); 

mean? Does it mean that a linked list of Node objects is being created and can be in the Queue?

I am taking open courseware to learn about Data Structures and Algorithms and I am a beginner. Thanks!

Upvotes: 1

Views: 2860

Answers (4)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136162

This is because java.util.LinkedList implements java.util.Queue but it is not a java.util.Stack though it has push and pop methods. Stack is a legacy class and its usage is not recommended, but if you still want to use it, this is the way to go

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

Upvotes: 2

John3136
John3136

Reputation: 29266

Queue<Node> queue says that variable queue is of type "Queue of Nodes". Queue is an interface not a class.

Java's LinkedList class implements the Queue interface, so queue = new LinkedList<Node>(); is perfectly ok.

The Java Stack is an actual class that doesn't implement the Queue interface, so you can't just substitute it in.

Upvotes: 2

Greg
Greg

Reputation: 1719

Does it mean that a linked list of Node objects is being created and can be in the Queue?

No it means that the underlying datastructure uses for the Queue is a LinkedList, and that you can add object of type Node

You should read up on generics if your are not familiar with this construct LinkedList<Node>()

Upvotes: 1

Mark Peters
Mark Peters

Reputation: 81164

In Java, for legacy reasons, Stack is a class, not an interface. So a LinkedList cannot be assigned to a variable of type Stack.

The Deque interface declares LIFO operations (although it also declares FIFO operations), and LinkedList implements Deque.

When you do

queue = new LinkedList<Node>();

you're creating a LinkedList but are referencing it via the type Queue, such that only the FIFO operations are exposed. This would ensure that later, other implementations of Queue could by swapped in by changing only the line above.

Upvotes: 4

Related Questions