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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With