1

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!

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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>();

Comments

2

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.

1 Comment

Thanks. Then is it OK to declare like this- Stack<Integer[]> intStack = new Stack<Integer[]>(); ? As in, the Stack class implements an array of integers?
1

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>()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.