How does java.util.queue implementation use LIFO?

In the Java doc:

[...] Among the exceptions are priority queues, order elements according to the provided comparator, or natural ordering of elements, as well as LIFO queues (or stacks) that order LIFO elements (last-in-first-out)

How does java.util.queue implementation use LIFO instead of FIFO ?

+8
source share
6 answers

Stack and LinkedList are offered here only for collections. A queue is not a collection. It is part of the concurrency package and can be used with file pools.

I just checked and read the javadoc that you specified. I believe that the only way to use the LIFO queue is to use the priority queue using a specialized comparator that compares the elements according to the insertion time in the reverse order.

+4
source

You can use any Deque as a LIFO queue using the Collections.asLifoQueue method:

 Queue<Integer> arrayLifoQueue = Collections.asLifoQueue(new ArrayDeque<Integer>()); Queue<Integer> linkedListLifoQueue = Collections.asLifoQueue(new LinkedList<Integer>()); 
+16
source

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

+8
source

A queue is a data structure that uses the First-In-First-Out technique.

Here's a useful link: magi.toolkit.util.queue LIFOQueue Class

Implementation of the queue "Last In, First Out". Basically, a LIFO Queue is a stack.

+2
source

Deque can be used as LIFO or FIFO

+2
source

Implementation of the queue can be based on FIFO , priorities and LIFO - official documentation says this.

When the programmer first sees the " Queue ", he automatically considers that " it must be a FIFO order " ( or, ultimately, a priority order ). But, as the documentation says, it should be possible to use the Queue interface to streamline the LIFO. Let me explain to you how this 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, the Queue interface can also be used as a LIFO.

+1
source

Source: https://habr.com/ru/post/893608/


All Articles