Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How implementation of java.util.queue uses LIFO?

In Java doc:

[...] Among the exceptions are priority queues, which order elements according to a supplied comparator, or the elements' natural ordering, and LIFO queues (or stacks) which order the elements LIFO (last-in-first-out)

How implementation of java.util.queue uses LIFO instead of FIFO?

like image 631
celsowm Avatar asked Jul 26 '11 16:07

celsowm


People also ask

How is LIFO implemented in queue?

Last In First Out queue Example In the case of last in the first out queue, the element that is entered last will be the first to come out. To work with LIFO, i.e., last in the first out queue, we need to import the queue module and make use of the LifoQueue() method.

Is Java queue FIFO or LIFO?

Stack and Queue both are Linear Data Structures. Stack follows the LIFO principle i.e. Last In First Out. Queue follows the FIFO principle i.e. First In First Out.

Do queues use LIFO?

Stacks and queues are both data structures that hold a list of elements. However, there is a key difference in how they work. A queue is first in, first out or FIFO. On the other hand, a stack is last in, first out or LIFO.

What is the implementation of queue in Java?

Answer: Queue in Java is a linear ordered data structure that follows FIFO (First In, First Out) ordering of elements. This means that the element inserted first in the queue will be the first element to be removed. In Java, the queue is implemented as an interface that inherits the Collection interface.


2 Answers

Implementation of the Queue can base on FIFO, priorities and LIFO - that is what official documentation says.

When a programmer first sees "Queue" he automatically thinks "it must be FIFO order" (or eventually prioritized order). But as documentation says there must be possibility to use Queue interface for LIFO ordering. Let me explain you how it can be done.

// FIFO queue usage
Queue<Integer> queue = new LinkedList<>();
queue.add(1);
queue.add(2);

queue.remove(); // returns 1
queue.remove(); // returns 2

// LIFO queue usage
Queue<Integer> queue = Collections.asLifoQueue(new ArrayDeque<>());
queue.add(1);
queue.add(2);

queue.remove(); // returns 2
queue.remove(); // returns 1

As you can see depending on the implementation, Queue interface can be used also as a LIFO.

like image 182
Adrian Malik Avatar answered Sep 23 '22 20:09

Adrian Malik


You can use a java.util.LinkedList and use the pop() and push() methods and use it like a stack, which is a LIFO queue.

like image 44
Oscar Gomez Avatar answered Sep 23 '22 20:09

Oscar Gomez